この記事では「The Swift Programming Language」を1から読んだ感想とか発見を書いてみようと思います。
「The Swift Programming Language」とはSwiftの公式ドキュメントでiBooksや下ページで見る事ができます。
The Swift Programming Language (Swift 2.1): About Swift
読んだ所
今回はProtocols
という項目を読みました。
The Swift Programming Language (Swift 2.1): Protocols
学んだこと
protocolでのプロパティーの宣言
protocolではcomputed propertyの宣言ができます。
protocol Protocol { var value: String { get } }
プロトコルでsetがなくても、クラスではsetを使う事ができます。
protocol Protocol { var value: String { get } } class Class: Protocol { var value: String { get { return "" } set {} } }
プロトコルでsetがあってクラスでない場合はエラーになります。
protocol Protocol { var value: String { get set } } class Class: Protocol { var value: String { get { return "" } } }
classを継承
プロトコルはclassを継承する事ができます。
classを継承した場合、structやenumで使えなくなります。
protocol Protocol: class { var value: String { get } }
Protocol Composition
protocol<Protocol1, Protocol2>
という型で宣言すると、Protocol1とProtocol2を満たした物以外は代入できません。
protocol Protocol1 { var value: String { get } } protocol Protocol2 { var value: String { get } } class Class: Protocol1, Protocol2 { var value: String { get { return "" } set {} } } let value: protocol<Protocol1, Protocol2> = Class()
optionalなメソッド
@objcキーワードを付ける事でoptionalなメソッドを宣言できます。
@objc protocol Protocol { optional func method() } class Class: Protocol { @objc func method() {} }
optionalと同等の事は、extensionでメソッドを実装することで実現できます。
protocol Protocol { func method() } extension Protocol { func method() {} } class Class: Protocol { }