Introducing protocol extensions

You briefly saw extensions in the previous chapters. They let you add additional members to a type:

extension String { func shout() {

print(uppercased())

}

}

"Swift is pretty cool".shout()

Here, you’re extending the String type itself to add a new method. You can extend any type, including ones that you didn’t write yourself. You can have any number of extensions on a type.

You can define a protocol extension using the following syntax:

protocol TeamRecord { var wins: Int { get } var losses: Int { get }

var winningPercentage: Double { get }

}

extension TeamRecord { var gamesPlayed: Int {

return wins + losses

}

}

Similar to the way you extend a class, struct or enum, you use the keyword extension followed by the name of the protocol you are extending. Within the extension’s braces, you define all the additional members of the protocol.

The biggest difference in the definition of a protocol extension, compared to the protocol itself, is that the extension includes the actual implementation of the member. In the example above, you define a new computed property named gamesPlayed that combines wins and losses to return the total number of games played.

Although you haven’t written code for a concrete type that’s adopting the protocol, you can use the members of the protocol within its extension. That’s because the compiler knows that any type conforming to TeamRecord will have all the members required by TeamRecord.

Now you can write a simple type that adopts TeamRecord, and use gamesPlayed

without the need to reimplement it:

struct BaseballRecord: TeamRecord { var wins: Int

var losses: Int

var winningPercentage: Double {

return Double(wins) / (Double(wins) + Double(losses))

}

}

let sanFranciscoSwifts = BaseballRecord(wins: 10, losses: 5) sanFranciscoSwifts.gamesPlayed // 15

Since BaseballRecord conforms to TeamRecord you have access to gamesPlayed, which was defined in the protocol extension.

You can see how useful protocol extensions can be to define “free” behavior on a protocol — but this is only the beginning. Next, you’ll learn how protocol extensions can provide implementations for members of the protocol itself.

results matching ""

    No results matching ""