Swift Cast Generics Type

六月ゝ 毕业季﹏ 提交于 2019-12-24 04:04:28

问题


I'm trying to cast a generic type to its 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>

But on the line

let v = c as Test<AnyObject>

I get 'Foo' is not identical to 'AnyObject'

While I can do that with built-in Arrays

let array1 = [Foo(), Foo()]
let array2 = array1 as [AnyObject]

回答1:


Arrays are special-cased in Swift to be able to have this behaviour. You won't be able to replicate it with your own classes, unfortunately.

To get similar behaviour, you could give your type another init method:

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

Note though that this is unsafe (i.e. will assert at runtime) in cases where you want to convert to an incompatible type (and the alternative, a failable initializer, will also have complications)



来源:https://stackoverflow.com/questions/29493819/swift-cast-generics-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!