danglingpointer
danglingpointer

Reputation: 712

Swift Generics: Constraining Argument Types

Coming from a C++ background (templates), I'm struggling to understand why the following piece of Swift code (generics) does not compile:

func backwards<T>(array: [T]) -> [T] {
    let reversedCollection = array.sort(>)

    return reversedCollection
}

The way I understand it is that T is a generic type on which I do not put any constraint (<T>) and declare array to be of type Array<T>. Yet this produces the following error:

Ambiguous reference to member 'sort()'

I understand that constraints can be put on the generic type using protocols. However, in this case, I don't want any constraint on T. Rather, I want to constrain the type of the first parameter.

I've been reading Apple's documentation on Generic Types for a few hours now but I'm still not much wiser. I have the impression that this is not possible and constraints are put solely on the declared types, but that's as far as I got.

So the question is: If possible, how do I put constraints on the types of the function arguments? If not, how do I achieve the same result?

Upvotes: 3

Views: 135

Answers (1)

Vatsal
Vatsal

Reputation: 18201

sort(>) is legal only when Element is Comparable. Since the element type of [T] is T, T must conform to Comparable in order for the array [T] to be sortable via >:

func backwards<T: Comparable>(array: [T]) -> [T] {
    let reversedCollection = array.sort(>)

    return reversedCollection
}

Upvotes: 3

Related Questions