我仍然有些困难理解Swift中泛型的一些细微差别。我定义了以下类型:
protocol SomeProtocol {
func setValue(value: Int)
}
class ProtocolLabel : UILabel, SomeProtocol {
func setValue(value: Int) {
}
}
class ProtocolImageView : UIImageView, SomeProtocol {
func setValue(value: Int) {
}
}
viewForValue(2) 现在我定义了以下函数。我希望T是符合SomeProtocol协议的UIView。
func viewForValue<T where T: SomeProtocol, T: UIView>(param: Int) -> UIView {
var someView: T
if param > 0 {
someView = ProtocolLabel() as T
} else {
someView = ProtocolImageView() as T
}
someView.setValue(2)
someView.frame = CGRectZero
return someView
}
然而,当我执行此代码时,出现以下编译错误:
viewForValue(2) // <-- Type 'UIView' does not conform to protocol 'SomeProtocol'
看起来在where子句中,我无法指定一个未实现协议的类。这是为什么呢?
谢谢提前。