LoginSignup
0
2

More than 3 years have passed since last update.

Swift protocol メモ

Last updated at Posted at 2019-01-27

protocolとは

interfaceみたいなもの。
classstructenumで使える。
複数適用可能!
delegateで使う。

protocolで変数・関数の宣言のみして、型を作成。
その後、protocolを継承した先のclass, struct, enumで定義。

使用例

procotol使用例
protocol Animal {
    var name: String { get }
    var age: Int { set get }
    func nakiGoe() -> String
}
procotol使用例
struct Dog: Animal {
    let name = "Pochi"
    var age = 3
    func nakiGoe() -> String {
        return "わん!"
    }
}

let dog = Dog()
dog.name
dog.age
dog.nakiGoe()

struct Cat: Animal {
    let name = "Tama"
    var age = 2
    func nakiGoe() -> String {
        return "にゃ〜ん"
    }
}

protocolはinterface(とほぼ同等)なので、protocolで宣言した変数・関数を継承先のクラスで実装すれば良い。

...protocolで定義した物の中で、デフォルト値が存在する場合、あらかじめextensionで宣言しておく

extension Animal {
    func nakiGoe() -> {
        return "でふぉると~~"
    }
}

protocolを使用するメリット・目的

構造体で使える

Swiftの構造体は構造体を継承できないので、protocolでやってしまう。

構造体は値を定義する変数群?なので、ロジック部分では多用する。ので、protocolで宣言としてまとめておくとすっきりする。

インタフェース(protocol)と実体(Object)を切り離せる

まとめ

protocolを使用すれば、可読性が上がる

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2