Kam*_*tka 15 inheritance protocols objective-c ios swift
在Objective-C中,您可以将类型定义为给定类的类并实现协议:
- (UIView <Protocol> *)someMethod;
Run Code Online (Sandbox Code Playgroud)
这将告诉返回的值someMethod是UIView实现给定协议Protocol.有没有办法在Swift中强制执行类似的操作?
Col*_*aff 10
你可以这样做:
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
}
Run Code Online (Sandbox Code Playgroud)
这定义了一个函数,它返回一个'SomeType'类型的对象和协议'SomeProtocol',并返回一个符合这些条件的对象.
| 归档时间: |
|
| 查看次数: |
9691 次 |
| 最近记录: |