altralaser altralaser - 10 months ago 61
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) {

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 Source

The easiest way is the use the standard closure

public func sort(comparator : (T, T) -> Bool) {

and constrain the generic type to the Comparable protocol

class ArrayList<T : Comparable>

Then you can use this code

let arrayList = ArrayList<Int>()

arrayList.sort { $0 < $1 }

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