LoginSignup
2
1

More than 5 years have passed since last update.

protocolで宣言されたassociatedtypeの型を判定する

Last updated at Posted at 2017-12-06

この記事はyurueアドベントカレンダーの7日目の記事です!

SwiftでAPIクライアントを書いていて、リクエストごとにクラス・構造体を作成した経験はありませんか?
そのリクエストについて記載したものの中には恐らく、Responseの型が記述されているのではないでしょうか。
今回は、protocolで宣言されたassociatedtypeの型を判定するサンプルを書こうと思います。

ソースコード

playground
protocol P {
    associatedtype Response
}

func typeDetect<T: P>(instance: T) {
    switch T.Response.self {
    case is String.Type:
        print("String")
    case is Int.Type:
        print("Int")
    default:
        print("else")
    }
}

class C1: P {
    typealias Response = String
}

class C2: P {
    typealias Response = Int
}

let c1 = C1()
let c2 = C2()

typeDetect(instance: c1) // String
typeDetect(instance: c2) // Int
2
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
2
1