I think the Swift development team presented a developer forum on how it would be nice to give a second example as a shorthand for the first. However, I think this will still be a common function - just a shorthand for declaring one?
How would it be otherwise? As the other answers pointed out, Equatable can only be used in general terms. But let's take an example that should not be. Like this:
func f<T: Printable>(t: T) { // do some stuff }
different from this:
func g(p: Printable) {
The difference is that f defines a family of functions that are generated at compile time, regardless of the type of what is passed as t , replaced by t . * Therefore, if you passed in Int , it would be as if youd wrote a version of func f(t: Int) { … } . If you go to Double , it will be like writing func f(t: Double) { … }
* This is an oversimplification, but continue with it for now ...
On the other hand, g is just one function that, at run time, can only accept a reference to the Printable protocol.
In practice, the differences are almost imperceptible. For example, if you pass t inside f to another function, it acts like this:
func f(i: Int) {
So for example:
func h(i: Int) { println("An Int!") } func h(p: Printable) { println("A Printable!") } func f<T: Printable>(t: T) { h(t) } h(1)
You can see the difference in the smallest ways:
func f<T: Printable>(t: T) { println(sizeof(t)) } f(1 as Int8)
The biggest difference is that they can return the actual generic type, not the protocol:
func f<T: Printable>(t: T) -> T { return t } func g(p: Printable) -> Printable { return p } let a = f(1)
This last example is the key to understanding why protocols with related types can only be used in general terms. Suppose you wanted to make your own implementation of first :
func first<C: CollectionType>(x: C) -> C.Generator.Element? { if x.startIndex != x.endIndex { return x[x.startIndex] } else { return nil } }
If first not a generic function and just a regular function that received a CollectionType protocol argument, how could it change what it returned?