本文介绍了Swift:type必须实现协议并且是给定类的子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Objective-C中,您可以将类型定义为给定类的类并实现协议:
In Objective-C, you could define a type as being of a given class and implementing a protocol:
- (UIView <Protocol> *)someMethod;
这将告诉 someMethod
是 UIView
实现给定的协议协议
。有没有办法在Swift中强制执行类似的东西?
This would tell that the value returned by someMethod
was a UIView
implementing a given protocol Protocol
. Is there a way to enforce something similar in 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',并返回一个符合这些条件的对象。
This defines a function that returns an object of type 'SomeType' and protocol 'SomeProtocol' and returns an object that adheres to those conditions.
这篇关于Swift:type必须实现协议并且是给定类的子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!