the following code answer: https://stackoverflow.com/a/28191539/4096655
public class synchronizedarray<t> { private var array: [t] = [] private let accessqueue = dispatch_queue_create("synchronizedarrayaccess", dispatch_queue_serial) public func append(newelement: t) { dispatch_async(self.accessqueue) { self.array.append(newelement) } } public subscript(index: int) -> t { set { dispatch_async(self.accessqueue) { self.array[index] = newvalue } } { var element: t! dispatch_sync(self.accessqueue) { element = self.array[index] } return element } } } var = synchronizedarray<int>() a.append(1) a.append(2) a.append(3) // can empty non-thread safe access println(a.array) // thread-safe synchonized access println(a[0]) println(a[1]) println(a[2])
i doing having trouble setting sort pass array of generics. ideally i'd sortinplace not sure how it.
if want sort wrapped array, 1 way constrain t
type conforming comparable
. if add restriction, sorting function easy implement, ask array sort itself:
public class synchronizedarray<t: comparable> { ... public func sortinplace() { array.sortinplace(<) }
for custom classes, need add extension conforming comparable
, , overload ==
, <
operators (reference here)
extension myclass: comparable { } func ==(lhs: myclass, rhs: myclass) -> bool { } func <(lhs: myclass, rhs: myclass) -> bool { } var = synchronizedarray<myclass>()
Comments
Post a Comment