We want to create a shortcut to access the members of the party. Subscripts are very useful to generate shortcuts to access members of any array, collection, list, or sequence. Subscripts can define getter and/or setter methods that 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. 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:
subscript(index: UInt) -> MemberType? { get }
We included the subscript
keyword followed by the argument name and its required type—which is the returned type, MemberType?
—and the...