在Objective-C中,您可以将类型定义为给定类并实现协议:
- (UIView <Protocol> *)someMethod;
这将表明返回的值someMethod是UIView实现给定协议的值Protocol。有没有办法在Swift中执行类似的操作?
someMethod
UIView
Protocol
您可以这样做:
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”的对象,并返回符合这些条件的对象。