假设我有这些协议:
protocol SomeProtocol {
}
protocol SomeOtherProtocol {
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我想要一个采用泛型类型的函数,但该类型必须符合SomeProtocol我可以做的:
func someFunc<T: SomeProtocol>(arg: T) {
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
但有没有办法为多个协议添加类型约束?
func bothFunc<T: SomeProtocol | SomeOtherProtocol>(arg: T) {
}
Run Code Online (Sandbox Code Playgroud)
类似的东西使用逗号,但在这种情况下,它会启动一个不同类型的声明.这是我尝试过的.
<T: SomeProtocol | SomeOtherProtocol>
<T: SomeProtocol , SomeOtherProtocol>
<T: SomeProtocol : SomeOtherProtocol>
Run Code Online (Sandbox Code Playgroud) 我想用一个类方法实现一个协议,该方法将实现类的数组作为参数.例如这样的事情:
protocol MyProtocol {
static func foo(verticies: [Self]) -> Int
}
class MyClass : MyProtocol {
class func foo(verticies: [MyClass]) -> Int {
return 42
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试这个时,我收到以下错误:
协议'MyProtocol'要求'foo()'不能被非最终'MyClass'类满足,因为它在非参数非结果类型中使用'Self'
但是如果我使用MyClass类型的对象而不是数组,这可以很好地工作:
protocol MyProtocol {
static func foo(verticies: Self) -> Int
}
class MyClass : MyProtocol {
class func foo(verticies: MyClass) -> Int {
return 42
}
}
Run Code Online (Sandbox Code Playgroud)
为什么这不适用于数组类型,并且有正确的方法吗?
swift ×2