Generic subscripts
Prior to Swift 4, if we wanted to use generics with a subscript, we had to define the subscript at the class or structure level. This forced us to make generic methods when it felt like we should be using subscripts. Starting with Swift 4, we can create generic subscripts, where either the subscript's return type or its parameters may be generic. Let's look at how we can create a generic subscript. In this first example, we will create a subscript that will accept one generic parameter:
subscript<T: Hashable>(item: T) -> Int {
return item.hashValue
}
When we create a generic subscript, we define the placeholder type after the subscript
keyword. In the previous example, we define the T
placeholder type and use a type constraint to ensure that the type conforms to the Hashable
protocol. This will allow us to pass in an instance of any type that conforms to the Hashable
protocol.
As we mentioned at the start of this section, we...