The Swift standard library uses protocols extensively, in ways that may surpriseyou. Understanding the roles protocols play in Swift will not only help you learn howto do things the "Swifty" way—it might also teach you new ways to write clean,decoupled code.
Equatable and comparable
Some of the simplest Swift code you can write involves comparing two integers withthe == operator:
let a = 5
let b = 5
a == b // true
You can, of course, do the same thing with strings:
let swiftA = "Swift"
let swiftB = "Swift"
swiftA == swiftB // true
You cannot, however, use the == operator on just any type. Suppose you wrote astruct that represents a team's record and wanted to determine if two records we equal:
struct Record {
var wins: Int
var losses: Int
}
let recordA = Record(wins: 10, losses: 5)
let recordB = Record(wins: 10, losses: 5)
recordA == recordB // Build error!
You can't apply the == operator to the struct you just defined, but why?
Recall that Int and String are structs just like Record, and their use of the equalityoperator isn't simply "magic" reserved for standard Swift types—you can, in fact,extend it to your own code!
Both Int and String conform to the Equatable protocol, which is a protocol in thestandard library that defines a single function:
protocol Equatable {
func ==(lhs: Self, rhs: Self) -> Bool
}
You can apply this protocol to the TeamMember struct:
extension Record: Equatable {
func ==(lhs: Record, rhs: Record) -> Bool {
return lhs.wins == rhs.wins && lhs.losses == rhs.losses
}
Here, you've extended the Record type. With extensions, you can add additionalmethods or properties to an existing type. In this case, you're adding protocolconformance to Record.
Note: You'll learn more about extensions very soon in Chapter 20, "Protocol-Oriented Programming."
Here, you're defining the == operator for comparing two Record instances. In thiscase, two records are equal if they have the same number of wins and losses.
Now, you're able to use the == operator to compare two Record types, just like youcan with String or Int:
let recordA = Record(wins: 10, losses: 5)
let recordB = Record(wins: 10, losses: 5)
recordA == recordB // True
Similar protocols exist for other operators, such as <, <=, >= and >. These operators
are defined in the Comparable protocol, which inherits from Equatable:
protocol Comparable : Equatable {
func <(lhs: Self, rhs: Self) -> Bool
func <=(lhs: Self, rhs: Self) -> Bool
func >=(lhs: Self, rhs: Self) -> Bool
func >(lhs: Self, rhs: Self) -> Bool
}
By adding the comparable protocol to Record, you can not only check equalitybetween records, you can determine if one record has more wins than the other:
extension Record: Comparable {
func <(lhs: Record, rhs: Record) -> Bool {
let lhsPercent = Double(lhs.wins) / (Double(lhs.wins) +Double(ls.losses))
let rhsPercent = Double(rhs.wins) / (Double(rhs.wins) +Double(rhs.losses))
return lhsPercent < rhsPercent
}
let team1 = Record(wins: 23, losses: 8)
let team2 = Record(wins: 23, losses: 8)
let team3 = Record(wins: 14, losses: 11)
team1 < team2 // falseteam1 > team3 // true
Your implementation of < compares the overall win percentages of the two records.If record A has a lower win percentage than record B, then that's considered "less than."
Note: You only defined < but what about >? Similarly, you defined == but whatabout != for inequality? Swift gives you a helping hand here and automaticallygenerates those other comparison operators. If you read the documentationfor Equatable and Comparable, you'll see it tells you that only == and < are needed.
"Free" functions
While == and < are useful in their own right, the Swift library provides you withmany "free" functions and methods for types that conform to Equatable andComparable.
For any collection you define, such as an Array, that contains a Comparable type,you have access to methods such as sort() that are part of the standard library:
let leagueRecords = [team1, team2, team3]
leagueRecords.sort()
// {wins 14, losses 11}
// {wins 23, losses 8}
// {wins 23, losses 8}
Since you've given Record the ability to compare two elements, the standard libraryhas all the information it needs to sort each element in an array!
As you can see, implementing Comparable and Equatable gives you quite an arsenalof tools:
leagueRecords.maxElement() // {wins 23, losses 8}
leagueRecords.minElement() // {wins 23, losses 8}
leagueRecords.startsWith([team1, team2]) // true
leagueRecords.contains(team1) // true
Other useful protocols
While learning all of the Swift standard library isn't vital to your success as a Swiftdeveloper, there are a few other important protools that you'll find useful in almostany project.
Hashable
The Hashable protocol is a requirement for any type you want to use as a key to aDictionary or a member of a Set:
protocol Hashable : Equatable {
var hashValue: Int { get }
}
It provides a single unique value you can use to represent an object. A Dictionary requires keys to be unique, and you can use hashValue to determine if a key existsin the dictionary, needs to be added, or if the value exists and needs to be replaced.In a Set, you would use hashValue to ensure that the same element will only appearonce, if added multiple times.
To implement Hashable, you should return an integer for hashValue that'sguaranteed to be unique to a particular value. A good example of this is thestudentId from the Student example:
extension Student: Hashable {
var hashValue: Int {
return studentId
}
}
You can now use the Student type in a Set or Dictionary:
let john = Student(firstName: "Johnny", lastName: "Appleseed")// Dictionary
let lockerMap: [Student: String] = [john: "14B"]// Set
let classRoster: Set<Student> = [john, john, john, john]
classRoster.count // 1
BooleanType
When you use an if statement, you typically use a Bool as an argument:
let isSwiftCool = true
if isSwiftCool {
print("I agree!")
}
One of the interesting "tricks" Swift uses in its protocol-heavy language design isthat if statements don't actually require a Bool value, but instead a type thatconforms to the BooleanType protocol:
protocol BooleanType {
var boolValue: Bool { get }
}
This is possible because Swift uses structs for almost all of its core types, includingBool. In the standard library, the Bool struct conforms to BooleanType and simplyreturns itself for boolValue!
The flexibility afforded by using a protocol instead of the concrete Bool type allowsyou to create your own type that you can use in place of a Bool:
extension Record: BooleanType {
var boolValue: Bool {
return wins > losses
}
}
You can now use the Record struct directly within an if statment that will evaluateto true if the record is a winning record:
if Record(wins: 10, losses: 5) {
print("winning!")
} else {
print("losing :(")
}
CustomStringConvertible
While not as important as the previous protocol, the CustomStringConvertibleprotocol can help log and debug your objects.
When you call print() with an object such as Record, Swift prints a generic textrepresentation of the object:
let record = Record(wins: 23, losses: 8)
print(record)// {wins 23, losses 8}
The CustomStringConvertible has only a description property, which customizeshow the object is represented both within print() statements and in the debugger:
protocol CustomStringConvertible {
var description: String { get }
}
By adopting CustomStringConvertible on the Record type, you can provide a morereadable representation:
extension Record: CustomStringConvertible {
var description: String {
return "\(wins) - \(losses)"
}
}
print(record)// 23 - 8
Frome: Swift Apprentice
网友评论