しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

【Swift】複数のプロトコルに準拠した変数の定義

下で定義された2つのプロトコルに準拠する型の書き方です。

protocol MyProtocol1 {}
protocol MyProtocol2 {}

複数のプロトコルへの準拠を表したい時は、下のように&を使います。

protocol MyProtocol1 {}
protocol MyProtocol2 {}
class MyClass: MyProtocol1, MyProtocol2 {}

let value: (MyProtocol1 & MyProtocol2) = MyClass()

下のように、引数・返り値に使う事もできます。

protocol MyProtocol1 {}
protocol MyProtocol2 {}
class MyClass: MyProtocol1, MyProtocol2 {}

class TestClass {
    var value1: (MyProtocol1 & MyProtocol2)?
    var value2: (MyProtocol1 & MyProtocol2) {
        return MyClass()
    }
    
    func myMethod(value: (MyProtocol1 & MyProtocol2)) -> (MyProtocol1 & MyProtocol2) {
        return MyClass()
    }
}

上のように何回も使う場合、typealiasで再定義するとすっきりします。

protocol MyProtocol1 {}
protocol MyProtocol2 {}
class MyClass: MyProtocol1, MyProtocol2 {}
typealias MyProtocols = MyProtocol1 & MyProtocol2

let value: MyProtocols = MyClass()