Swift Cast泛型类型 [英] Swift Cast Generics Type

查看:147
本文介绍了Swift Cast泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将泛型类型强制转换为其超类。

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>

但在行上

let v = c as Test<AnyObject>

我得到'Foo'不等于'AnyObject'

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

我可以用内置的数组

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


推荐答案

数组在Swift中是特殊的,可以有这种行为。

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.

为了得到类似的行为,你可以给你的类型另一个 init 方法:

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

注意,这是不安全的将在运行时断言)在您想要转换为不兼容类型(和备选,一个failable初始值,也将有并发症)

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)

这篇关于Swift Cast泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆