次のようなプロトコルがあるとします。
protocol SomeProtocol {
}
protocol SomeOtherProtocol {
}
さて、ジェネリック型を受け取る関数が必要で、その型が準拠している必要がある場合は、SomeProtocol
次のようにします。
func someFunc<T: SomeProtocol>(arg: T) {
// do stuff
}
しかし、複数のプロトコルに型制約を追加する方法はあるのでしょうか?
func bothFunc<T: SomeProtocol | SomeOtherProtocol>(arg: T) {
}
同様のことはコンマを使って行いますが、この場合は別の型の宣言を開始します。私が試したことは次のとおりです。
<T: SomeProtocol | SomeOtherProtocol>
<T: SomeProtocol , SomeOtherProtocol>
<T: SomeProtocol : SomeOtherProtocol>
ベストアンサー1
あなたはwhere句必要な数の要件(すべて満たす必要がある)をコンマで区切って指定できます。
スイフト2:
func someFunc<T where T:SomeProtocol, T:SomeOtherProtocol>(arg: T) {
// stuff
}
Swift 3 および 4:
func someFunc<T: SomeProtocol & SomeOtherProtocol>(arg: T) {
// stuff
}
または、より強力な where 句:
func someFunc<T>(arg: T) where T:SomeProtocol, T:SomeOtherProtocol{
// stuff
}
もちろん、プロトコル構成 (例: protocol<SomeProtocol, SomeOtherProtocol>
) を使用することもできますが、柔軟性は少し低くなります。
を使用するとwhere
、複数のタイプが関係するケースに対処できます。
複数の場所で再利用するためにプロトコルを作成したり、作成したプロトコルに意味のある名前を付けたりする必要がある場合もあります。
スイフト5:
func someFunc(arg: SomeProtocol & SomeOtherProtocol) {
// stuff
}
プロトコルが引数の隣にあるので、より自然に感じられます。