0

The following code is from this 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
            }
        }
        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.

Community
  • 1
  • 1
Fred Faust
  • 6,696
  • 4
  • 32
  • 55

1 Answers1

1

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>()
Cristik
  • 30,989
  • 25
  • 91
  • 127