swift 学习(10)Protocols

There’s one final type that can bridge common behaviors between structs, classes and enums. In fact, it is itself a user-defined named type: the protocol.
A protocol can be adopted by a class, struct, or enum — and when another type adopts a protocol, it’s required to implement the methods and properties defined in the protocol. Once a type implements all members of a protocol, the type is said to conform to the protocol.
协议可以由类,结构或枚举采用 - 当另一种类型采用协议时,需要实现协议中定义的方法和属性。 一旦类型实现了协议的所有成员,那么该类型被认为符合协议。

Methods in protocols

在协议中定义的方法都不需要实现。

enum Direction {
  case left
  case right
}
protocol DirectionalVehicle {
  func accelerate()
  func stop()
  func turn(direction: Direction)
  func description() -> String
}

Properties in protocols

在协议中声明的属性,需要明确的标记是get 或者 get 和 set。
协议中定义的属性,协议本身并不关心具体如何实现,你可以使用计算属性实现、也可以使用存储属性存储。所有的协议定义属性都要明确要求属性是只读还是 读与写。

protocol Account {
    var value: Double { get set }
    init(initialAmount: Double)
    init?(transferAccount: Account)
}

class BitcoinAccount: Account {
    var value: Double
    required init(initialAmount: Double) {
        value = initialAmount
    }
    required init?(transferAccount: Account) {
        guard transferAccount.value > 0.0 else {
            return nil
        }
        value = transferAccount.value
    }
}
var accountType: Account.Type = BitcoinAccount.self
let account = accountType.init(initialAmount: 30.00)

Protocol inheritance

协议定义时可以继承自其他的协议。

Implementing protocols

protocol Vehicle {
    func accelerate()
    func stop()
}
class Bike: Vehicle {
    var peddling = false
    var brakesApplied = false
    func accelerate() {
        peddling = true
        brakesApplied = false
    }
    func stop() {
        peddling = false
        brakesApplied = true
    }
}

Associated types in protocols

protocol WeightCalculatable {
    associatedtype WeightType
    func calculateWeight() -> WeightType
}


class HeavyThing: WeightCalculatable {
    // This heavy thing only needs integer accuracy
    typealias WeightType = Int
    func calculateWeight() -> Int {
        return 100
    }
}

class LightThing: WeightCalculatable {
    // This light thing needs decimal places
    typealias WeightType = Double
    func calculateWeight() -> Double {
        return 0.0025
    }
}

因为swift 具有类型推导,所有上面的 typealias WeightType 可以不写,直接使用。

Implementing multiple protocols

每个类只能继承自一个类,但是它可以遵守多个协议。

class Bike: Vehicle, Wheeled {
  // Implement both Vehicle and Wheeled
}

类也可以使用扩展接收协议。这样就很好的实现了代码分离。

class Bike {
    var wheelNumber : String = ""
    var wheelSize = 0.0
    init(wheelNumber:String,wheelSize:Double) {
        self.wheelSize = wheelSize
        self.wheelNumber = wheelNumber
    }
}

extension Bike : Hashable
{
    var hashValue: Int {
        return self.wheelNumber.hashValue
    }
}
extension Bike : CustomStringConvertible
{
    
    var description: String {
        return "\(self.wheelNumber) "
    }
}

Requiring reference semantics

Protocols can be adopted by both value types (structs and enums) and reference types (classes), so you might wonder if protocols have reference or value semantics.
协议可以由两种值类型(结构和枚举)和引用类型(类)采用,因此您可能想知道协议是否具有引用或值语义。

protocol Named {
    var name: String { get set }
}
class ClassyName: Named {
    var name: String
    init(name: String) {
        self.name = name
    }
}
struct StructyName: Named {
    var name: String
}

//指针指向同一块内存地址。
var named: Named = ClassyName(name: "Classy")
var copy = named
named.name = "Still Classy"
named.name // Still Classy
copy.name // Still Classy

//值COPY
named = StructyName(name: "Structy")
copy = named
named.name = "Still Structy?"
named.name // Still Structy?
copy.name // Structy

容易引起歧义。如果我们设计了一个专门让类引用的协议,可以在声明协议时加一个关键字

protocol Named: class {
  var name: String { get set }
}

这样就只有类可以引用该协议。

Protocols in the standard library

The Swift standard library uses protocols extensively in ways that may surprise you. Understanding the roles protocols play in Swift can help you write clean, decoupled “Swifty” code.

Equatable

如果是两个int类型常量 或者 stirng 类型的常量 的可以直接使用 == 进行比较操作的。但是struct 类型就不能直接使用 == 进行比较。

这是因为Int 和 String 引用了 Equatable 协议。
如何struct 也想使用 == 操作符,引用 Equatable 就行了。

struct Record {
  var wins: Int
  var losses: Int
}

extension Record: Equatable {
  static func ==(lhs: Record, rhs: Record) -> Bool                                  
    {   
        return lhs.wins == rhs.wins &&
             lhs.losses == rhs.losses
    } 
}

let recordA = Record(wins: 10, losses: 5)
let recordB = Record(wins: 10, losses: 5)
recordA == recordB // true

Key points

  • Protocols define a contract classes, structs and enums can adopt.协议定义了一个契约类,结构体和枚举可以采用。
  • By adopting a protocol, a type is required to conform to the protocol by implementing all methods and properties of the protocol.采用协议,需要实现协议的所有方法和属性来遵循协议的类型。
  • A type can adopt any number of protocols, which allows for a quasi-multiple inheritance not permitted through subclassing.数据可以通过使用多个协议来达到多继承的效果。
  • You can use extensions for protocol adoption and conformance.
  • The Swift standard library uses protocols extensively(大量的). You can use many of them, such as Equatable and Hashable, on your own named types.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,738评论 5 472
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,377评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,774评论 0 333
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,032评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,015评论 5 361
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,239评论 1 278
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,724评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,374评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,508评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,410评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,457评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,132评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,733评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,804评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,022评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,515评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,116评论 2 341

推荐阅读更多精彩内容