swift基础—协议和扩展(Protocols and Extensions)

使用“protocol”来声明一个协议。

protocol ExampleProtocol {

  var simpleDescription: String { get }

  mutating func adjust()

}

类、枚举和结构体都可以实现协议。

class SimpleClass: ExampleProtocol {

  var simpleDescription: String = "A very simple class."

  var anotherProperty: Int = 69105

  func adjust() {

    simpleDescription += "  Now 100% adjusted."

  }

}

var a = SimpleClass()

a.adjust()

let aDescription = a.simpleDescription

struct SimpleStructure: ExampleProtocol {

  var simpleDescription: String = "A simple structure"

  mutating func adjust() {

    simpleDescription += " (adjusted)"

  }

}

var b = SimpleStructure()

b.adjust()

let bDescription = b.simpleDescription

注意声明“SimpleStructure”时候“mutating”关键字用来标记一个会修改结构体的方法。“SimpleClass”的声明不需要标记任何方法,因为类中的方法通常可以修改类属性(类的性质)。

使用“extension”来为现有的类型添加功能,比如新的方法和计算属性。你可以使用扩展在别处修改定义,甚至是从外部库或者框架引入的一个类型,使得这个类型遵循某个协议。

extension Int: ExampleProtocol {

  var simpleDescription: String {

    return "The number \(self)"

  }

  mutating func adjust() {

    self += 42

  }

}

print(7.simpleDescription)

你可以像使用其他命名类型一样使用协议名——例如,创建一个有不同类型但是都实现一个协议的对象 合。当你处理类型是协议的值时,协议外定义的方法不可用。

let protocolValue: ExampleProtocol = a

print(protocolValue.simpleDescription)

// print(protocolValue.anotherProperty) // 去掉注释可以看到错误

即使“protocolValue”变量运行时的类型是“simpleClass”,编译器会把它的类型当做“ExampleProtocol”。这表示你不能调用类在它实现的协议之外实现的方法或者属性。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • SwiftDay011.MySwiftimport UIKitprintln("Hello Swift!")var...
    smile丽语阅读 3,857评论 0 6
  • 协议 与OC中一样,协议的关键字也是protocol 在Swift中,class(类)、struct(结构体)、e...
    pony23阅读 1,011评论 0 1
  • 132.转换错误成可选值 通过转换错误成一个可选值,你可以使用 try? 来处理错误。当执行try?表达式时,如果...
    无沣阅读 1,281评论 0 3
  • Swift 介绍 简介 Swift 语言由苹果公司在 2014 年推出,用来撰写 OS X 和 iOS 应用程序 ...
    大L君阅读 3,300评论 3 25
  • 放下头脑中根深蒂固的执念,放下对别人的操控,也不再靠别人的脸色过活,也不会再因别人无关痛痒的话语激怒自己的内在小孩...
    敏子慧慧阅读 156评论 0 0