swift

Swift 中的协议

2014-08-24  本文已影响0人  乐人曹

实例属性,实例方法,类方法,运算符,下标

语法

protocol SomeProtocol {
    // protocol definition goes here
}

struct SomeStructure: FirstProtocol, AnotherProtocol {
    // structure definition goes here
}

class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {
    // class definition goes here
}

属性

指定属性的 名字类型,以及 getterable or setterable

protocol SomeProtocol {
    var mustBeSettable: Int { get set }
    var doesNotNeedToBeSettable: Int { get }
}

protocol AnotherProtocol {
    class var someTypeProperty: Int { get set }
}

当一个属性被指定成 getterable 时,实现中可以成为 setterable
类属性用 class 表征,不管实现时,是结构还是类。

方法

和正常的方法定义一样(除了不能设置默认参数值)。

如果一个方法有 mutating 标记,实现时,类无须再添加该标记,结构和枚举依旧需要标记。

初始化器

协议中,和正常的初始化器定义一样。

类实现中,需要添加 require 标记。(如果该类被标记成 final,那 require 标记不需要)

Class-Only

protocol SomeClassOnlyProtocol: class, SomeInheritedProtocol {
    // class-only protocol definition goes here
}

协议组合

protocol<SomeProtocol, AnotherProtocol>

协议类型检查

@objc protocol HasArea {
  // do what you like
}

要想通过 is/as 来检查协议类型,必须给协议添加 @objc 标记(为了将这个协议暴露给 Objective-C 代码)。
另外,这样的协议只能用类来实现,而不能用结构和枚举。

可选需求

通过 optional 标记可选实现。
但要注意,也需要给协议标记 @objc

上一篇 下一篇

猜你喜欢

热点阅读