以下代码来自此答案: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
}
}
get {
var element: T!
dispatch_sync(self.accessQueue) {
element = self.array[index]
}
return element
}
}
}
var a = SynchronizedArray<Int>()
a.append(1)
a.append(2)
a.append(3)
// can be empty as this is non-thread safe access
println(a.array)
// thread-safe synchonized access
println(a[0])
println(a[1])
println(a[2])
我正在做一些非常喜欢但却无法设置排序以传递给泛型数组的东西。理想情况下,我喜欢sortInPlace但不知道该怎么做。
答案 0 :(得分:1)
如果要对包装的数组进行排序,则一种方法是将T
约束为符合Comparable
的类型。如果添加此限制,则可以轻松实现排序功能,只需要求数组自行排序:
public class SynchronizedArray<T: Comparable> {
...
public func sortInPlace() {
array.sortInPlace(<)
}
对于自定义类,您需要添加符合Comparable
的扩展名,并重载==
和<
运算符(参考here)
extension MyClass: Comparable {
}
func ==(lhs: MyClass, rhs: MyClass) -> Bool {
}
func <(lhs: MyClass, rhs: MyClass) -> Bool {
}
var a = SynchronizedArray<MyClass>()