Swift中的协议
Swift中的常用协议
Equatable
Equatable
协议用于相等的比较,遵守这个协议后必须对==
运算符进行重载。
struct Record: Equatable { var wins: Int var losses: Int } func ==(left: Record,right: Record) -> Bool { return left.wins == right.wins && left.losses == right.losses } let recordA = Record(wins: 10,losses: 5) let recordB = Record(wins: 10,losses: 5) recordA == recordB//true recordA != recordB//false
重载==
之后,!=
也可以正常使用
Comparable
Comparable
协议用于比较,只需要重载<
就可以了
struct Record: Equatable,Comparable { var wins: Int var losses: Int } func ==(left: Record,right: Record) -> Bool { return left.wins == right.wins && left.losses == right.losses } func <(left: Record,right: Record) -> Bool { if left.wins != right.wins { return left.wins < right.wins } return left.losses > right.losses }
Record
遵守Comparable
协议,表示其是一个可比较的对象。
var team1Record = Record(wins: 10,losses: 3) var team2Record = Record(wins: 8,losses: 5) var team3Record = Record(wins: 8,losses: 8) var records = [team1Record,team2Record,team3Record] records.sort()
customstringconvertible
遵循customstringconvertible
协议,只需要实现一个计算型的属性description
struct Record: Equatable,Comparable,customstringconvertible { var wins: Int var losses: Int var description: String { return "WINS: " + String(wins) + ",LOSSES: " + String(losses) } }
这时print(team1Record)
输出的结果就为:WINS: 10,LOSSES: 3
BooleanType
BooleanType
可以让一个类型被视为一个布尔值,需要覆盖一个boolValue
属性。
var boolValue: Bool { return wins > losses }
就可以这样使用if
语句:
if recordA { }
同样可以让基本类型实现BooleanType
协议,这样就可以直接来进行布尔判断,如下:
extension Int: BooleanType { public var boolValue: Bool { return self != 0 } } var wins = 0 if !wins { print("You never win!") }
面向协议编程
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。