LoginSignup
4
5

More than 5 years have passed since last update.

特定のプロトコルに準拠し、特定のクラスを継承しているクラスを返す

Posted at

class Hoge: PiyoObject, FooProtocol {}
class Fuga: PiyoObject, FooProtocol {}

PiyoObjectクラスを継承しつつ、FooProtocolに準拠している2つのクラスがある。
これを両方返すfactory methodを作りたい。

func makePiyoFoo<T: PiyoObject>() -> T where T: FooProtocol { 
 switch self {
   case .hoge: return Hoge() as T
   case .fuga: return Fuga() as T     
 }
}

Tで一回型のジェネリクスを取りつつ返り値でプロトコル準拠を保証すればOK

4
5
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
5