4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

swift Protocolで型宣言することで動的な型付けを実現する

Last updated at Posted at 2016-08-28

背景

swiftは強力な型付け言語であるため、全ての変数の型はコンパイル時には決定している必要がる。
ゆえに以下の様なコードがかけない。

compile_error.swift
struct A { }
struct B { }


// コンパイルエラー  mismatching types 'A' and 'B'
let o = genRandomBoolValue() ? A() : B()

Protocolで型宣言を行うとことで動的型付けの実現

上記の型A, Bを以下のように共通のProtocolを持つようにすれば、
実行時に型を動的に決定させることが出来ます。

dinamic_dispatching_type.swift
protocol P { 
    var name: String { get }
}

struct A: P { var name = "I am A" }
struct B: P { var name = "I am B" }

let o: P = genRandomBoolValue() ? A() : B()
print(o.name)

Protocolを型宣言で用いれる所

  • ローカル変数の型宣言
  • 関数の仮引数の型宣言
  • 関数の返り値の型宣言

デメリット

  • プロトコルで型宣言された変数は、プロトコルで定義されている機能のみ有効である。
      値として代入された型独自の機能を使う場合は、どこかでキャストする必要がある。
  • プロトコルで型宣言できるプロトコルが限られている。(Self, 関連型を持っていないプロトコルのみ)
4
1
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?