【发布时间】:2014-09-15 10:55:30
【问题描述】:
我仍然无法理解 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 子句中我无法指定不实现协议的类。这是为什么呢?
提前致谢。
【问题讨论】:
-
你可以试试这个:
标签: ios generics swift protocols