在Objective-C中,您可以将类型定义为给定类和实现协议的类型:
- (UIView <Protocol> *)someMethod;
这表明someMethod
返回的值是实现了给定协议Protocol
的UIView
。在Swift中是否有类似的强制要求方式呢?
- (UIView <Protocol> *)someMethod;
这表明someMethod
返回的值是实现了给定协议Protocol
的UIView
。在Swift中是否有类似的强制要求方式呢?
protocol SomeProtocol {
func someMethodInSomeProtocol()
}
class SomeType { }
class SomeOtherType: SomeType, SomeProtocol {
func someMethodInSomeProtocol() { }
}
class SomeOtherOtherType: SomeType, SomeProtocol {
func someMethodInSomeProtocol() { }
}
func someMethod<T: SomeType where T: SomeProtocol>(condition: Bool) -> T {
var someVar : T
if (condition) {
someVar = SomeOtherType() as T
}
else {
someVar = SomeOtherOtherType() as T
}
someVar.someMethodInSomeProtocol()
return someVar as T
}
这定义了一个函数,返回一个类型为 'SomeType' 和协议为 'SomeProtocol' 的对象,并返回符合这些条件的对象。
var v: T; v = MyView()
,即使 MyView 是 class MyView : UILabel, Protocol
,我仍会收到“MyView 无法转换为 T”的错误。 - Kamchatkafunc someMethod() -> T {
var someVar: T
someVar.someMethodInSomeProtocol() <-- 错误 "T 没有名为 'someMethodInSomeProtocol' 的成员"
return someVar as T
}
- Kamchatkafunc someMethod<T: SomeType, SomeProtocol>()
与func someMethod<T where T: SomeType, T: SomeProtocol>()
不同。我不明白为什么后者不起作用。 - Kamchatka