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 절에 내가 프로토콜을 구현하지 않는 클래스를 지정할 수 없습니다 것 같다 . 왜 그런가요?
미리 감사드립니다.
는이를 사용하려고 할 수 세그먼트 오류로 실패 : –
Greg