CustomStringConvertible
struct Point {
var x: Int
var y: Int
}
let p = Point(x: 4, y: 2)
print(p) // Point(x: 4, y: 2)
// 如果我们想打印变成 x = 10, y = 10
// 那么我们就要遵守 CustomStringConvertible 这个 协议
extension Point: CustomStringConvertible {
// 这个 protocol 只有一个约定定义一个名为description的属性
var description: String {
return "x = \(self.x), y = \(self.y)"
}
}
print(p) // x = 10, y = 10\n
Equatable
extension Point: Equatable {}
func == (lP: Point, rP: Point) -> Bool {
let equalX = lP.x == rP.x
let equalY = lP.y == rP.y
return equalX && equalY
}
let lP = Point(x: 10, y: 10)
let rP = Point(x: 10, y: 10)
// 不要以为是我们重载了 == 函数 就能自动推导出 !=
// 其实这都是 Equatable 这个 protocol 的功劳
// 当然我们如果要遵守 Equatable 这个 protocol 就必须实现 == 函 数 或者 != 函数
// 如果我们只是重载了 == 函数 是不能用 !=
if lP != rP {
print("unequal")
} else {
print("equal")
}
BooleanType
// 如何更优雅的判断该点是不是原点(0, 0)
// 来一起看下
extension Point: BooleanType {
// 遵守BooleanType这个protocol
// 这个protocol也只需要一个实现一个名为boolValue的属性
var boolValue: Bool {
return self.x == 0 && self.y == 0
}
}
let p = Point(x: 10, y: 10)
// 这样我们就能这样进行判断了
if p {
print("是原点(0, 0)")
} else {
print("不是原点")
}
Comparable
// 想遵守 Comparable 这个 protocol 必须遵守 Equatable
// 同时用必须实现 < 函数 或者 > 函数
extension Point: Comparable {}
// 同样 > 函数会自动推导出来
func < (lP: Point, rP: Point) -> Bool {
// 随意定义的规则 不必在意
let x = lP.x - rP.x
let y = lP.y - rP.y
return x < y
}
// 实现了 Comparable 我们就可以把 Point 放到 Array 中,同时支持使用各种排序方法
常见的几种系统的协议,遵循他们可以提高效率.欢迎补充!
网友评论