Swift: Protocols in the standard library

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,362评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,330评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,247评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,560评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,580评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,569评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,929评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,587评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,840评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,596评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,678评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,366评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,945评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,929评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,165评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,271评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,403评论 2 342

推荐阅读更多精彩内容