Tôi vẫn gặp sự cố khi hiểu một số sự tinh tế của generics trong Swift. Tôi xác định các loại sau:Loại không tuân theo giao thức
protocol SomeProtocol {
func setValue(value: Int)
}
class ProtocolLabel : UILabel, SomeProtocol {
func setValue(value: Int) {
}
}
class ProtocolImageView : UIImageView, SomeProtocol {
func setValue(value: Int) {
}
}
viewForValue (2) Bây giờ tôi đã xác định hàm sau. Tôi mong đợi T là UIView tuân thủ giao thức SomeProtocol.
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
}
Tuy nhiên, tôi nhận ra lỗi biên dịch sau khi tôi thực thi mã:
viewForValue(2) // <-- Type 'UIView' does not conform to protocol 'SomeProtocol'
Dường như trong mệnh đề mà tôi không thể xác định một lớp học mà không thực hiện các giao thức . Tại sao vậy?
Xin cảm ơn trước.
Bạn có thể thử sử dụng này: –
Greg