Swift中的协议

前端之家收集整理的这篇文章主要介绍了Swift中的协议前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

面向协议编程

原文链接:https://www.f2er.com/swift/322849.html

猜你在找的Swift相关文章