0

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.

0

1 Answer 1

1

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]
Sign up to request clarification or add additional context in comments.

3 Comments

Why would you restrict T to Comparable, you're disallowing non-comparable elements just because they can't be sorted with < and>? If anything, you could add an extension that only applies when T is comparable that offers a default sort function.
I know I just wanted to answer the question quite simply and avoid the Binary Operator < cannot be applied to... error message.
this will work fine without the restriction as well as long as T is Comparable. And if it isn't you shouldn't expect to be able to compare it using < and you can still compare it some other way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.