Creating shortcuts with subscripts
We want to create a shortcut to access the members of the party. Subscripts are very useful to generate shortcuts to access the members of any array, collection, list, or sequence. Subscripts can define getter and/or setter methods, which receive the argument specified in the subscript declaration. In this case, we will add a read-only subscript to allow us to retrieve a member of the party through its index value indicated within square brackets. Thus, the subscript will only define a getter method.
We will use UInt
as the type for the index argument because we don't want negative integer values, and the getter for the subscript will return an optional type. In case the index value received is an invalid value, the getter will return none
.
First, we will add the following line to the PartyProtocol
protocol body. The code file for the sample is included in the swift_3_oop_chapter_06_09
folder:
subscript(index: UInt) -> MemberType? { get }
We...