Swift Cast 泛型类型

标签 swift generics casting

我正在尝试将泛型类型转换为其父类(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/

相关文章:

swift - Swift 中的 NSTextField 行间距

ios - 如何在核心情节饼图中心添加图片和标题?

swift - 如何在 Swift 中一个接一个地显示 UIAlertController

java - 通用接口(interface)和通配符

java - 如何使 Java 方法变得通用?

swift - 转换为指定的通用函数参数

c++ - 用于具有不同签名的函数的枚举切换器

c - 获取与 C 中的 int val 关联的枚举名称。避免从 int 到 enum 的类型转换

swift - dispatch_async 与 dispatch_sync 在获取数据中的对比。 swift

c# - 使用通用类型保持代码组织