The CollectionType protocol methods
All the collections mentioned earlier—array, set and, dictionary—implement a CollectionType
protocol. Because of this, they are interchangeable. You can use any of them in places where a CollectionType
method is required. An example is a function with a CollectionType
parameter:
func useCollection<T: CollectionType>(x: T) { print("collection has \(x.count) elements") } let array = [1, 2, 3] let set: Set = [2, 2, 3, 4, 5] let dic = ["A" : 1, "B" : 2] useCollection(array) useCollection(set) useCollection(dic)
Protocol extensions
The other incredibly useful feature is protocol extensions. With protocol extensions, we can add implementations of methods and properties directly to the protocol. All types that conform to that protocol are able to use those methods for free. Let's add our own property to a CollectionType
method:
extension CollectionType { var middle: Self.Index.Distance { return count / 2 } } array.middle set.middle dic.middle
The...