O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Generic 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 can also ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required