제네릭으로 머리를 감싸는 데 문제가 있습니다. 내가 원하는 것은 각각 고유 한 관련 유형을 가진 제네릭 클래스 배열을 갖고 그에 따라 함수를 호출하는 것입니다. 다음과 같이 보일 것입니다.
class SomeGenericClass<U> {
func addCallback(callback: (U)->() ) { ... }
}
var array: [SomeGenericClass] // compile error
마지막 줄에서 오류가 발생하므로 수퍼 클래스가 필요하다는 것을 알았습니다. 나는 다음과 같이 시도했다.
class SuperClass {
func addCallback<V>(callback: (V)->() ) { ... }
}
class SomeGenericClass<U> {
func addCallback<V: U>(callback: (V)->() ) { ... } // compile error
}
var array: [SuperClass] // no compile error
이로 인해 오류가 발생 Type 'V' constrained to non-protocol, non-class type 'U'
합니다.
기본적으로 할 수 있기를 원합니다.
array.append(SomeGenericClass<UIImage>()) // array[0]
array.append(SomeGenericClass<Int>()) // array[1]
// Since array[0] is effectively of type SomeGenericClass<UIImage>, the compiler should understand that the close added if of type (UIImage)->(), and therefore that value is of type UIImage
array[0].addCallback { value in
someImageView.image = value
}
이 경우 슈퍼 클래스를 사용하는 것이 올바른 접근 방식입니까? 어떻게 구현해야합니까?
배열 멤버를 자체 변수에 저장하여이 문제를 해결했습니다. 즉, 내 배열을 다음과 같이 정의하는 대신 :
lazy var array: [SuperClass] = [
SomeGenericClass<UIImage>(),
SomeGenericClass<Int>(),
//etc...
]
나는 이것을 이렇게 정의했습니다.
lazy var genericFirst: SomeGenericClass<UIImage> = SomeGenericClass<UIImage>()
lazy var genericSecond: SomeGenericClass<Int> = SomeGenericClass<Int>()
// etc...
lazy var array: [SuperClass] = [
genericFirst,
genericSecond,
//etc...
]
이렇게하면 다음과 같이 원하는 제네릭에 액세스 할 수 있습니다.
genericFirst.addCallback { value in
// value is indeed of type UIImage
someImageView.image = value
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다