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!") }