我正在尝试将泛型类型转换为其父类(super class)。
class Foo : NSObject {
}
class Test<T> {
let value: T
init(_ value: T) {
self.value = value
}
}
let c = Test(Foo())
let v = c as Test<AnyObject>
但是在线
let v = c as Test<AnyObject>
我得到“Foo”与“AnyObject”不相同
虽然我可以使用内置数组来做到这一点
let array1 = [Foo(), Foo()]
let array2 = array1 as [AnyObject]
最佳答案
数组在 Swift 中是特殊的,以便能够具有这种行为。不幸的是,您将无法用自己的类(class)复制它。
要获得类似的行为,您可以为您的类型提供另一个 init
方法:
class Test<T> {
let value: T
init(_ value: T) {
self.value = value
}
init<U>(other: Test<U>) {
// in Swift 1.2 you will need as! here
self.value = other.value as T
}
}
let c = Test(Foo())
let v = Test<AnyObject>(other: c) // this will work ok
请注意,在您想要转换为不兼容类型的情况下,这是不安全的(即会在运行时断言)(替代方案,可失败的初始化程序,也会有并发症)
关于Swift Cast 泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29493819/