当前位置: 动力学知识库 > 问答 > 编程问答 >

swift - Add sort to array wrapping class

问题描述:

The following code is from this answer: http://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])

I am doing something very much like but am having trouble setting up a sort to pass to the array of generics. Ideally I'd like a sortInPlace but am not sure how to do it.

网友答案:

If you want to sort the wrapped array, then one way is to constrain T to a type conforming to Comparable. If you add this restriction, then a sorting function is easy to implement, simply ask the array to sort itself:

public class SynchronizedArray<T: Comparable> {

...

public func sortInPlace() {
    array.sortInPlace(<)
}

For custom classes, you need to add an extension conforming to Comparable, and overload the == and < operators (reference here)

extension MyClass: Comparable {

}

func ==(lhs: MyClass, rhs: MyClass) -> Bool {

}

func <(lhs: MyClass, rhs: MyClass) -> Bool {

}

var a = SynchronizedArray<MyClass>()
分享给朋友:
您可能感兴趣的文章:
随机阅读: