altralaser altralaser - 2 months ago 19
Swift Question

How to sort a typed array in swift?

I built a custom class which holds an "internal" array and offers some useful methods.

class ArrayList<T> {
private var array : Array<T>

public init() {
array = Array<T>()
}

public func add(element : T) {
array.append(element)
}

public func size() -> Int {
return array.count
}

...
}


Ok, that works fine for me so far.

But now I also want to have a method to sort the array. What I already have is the following:

public func sort(comparator : ?) {
array = array.sort(comparator)
}


The question mark stands for the parameter type and that is my problem: Which type must the parameter have? I read something about @noescape<,> but I can't get it to work!

I'm using Swift 2.2.

Answer

The easiest way is the use the standard closure

public func sort(comparator : (T, T) -> Bool) {
   array.sortInPlace(comparator)
}

and constrain the generic type to the Comparable protocol

class ArrayList<T : Comparable>

Then you can use this code

let arrayList = ArrayList<Int>()
arrayList.add(5)
arrayList.add(12)
arrayList.add(10)
arrayList.add(2)

arrayList.sort { $0 < $1 }

print(arrayList.array) // [2, 5, 10, 12]