快速向下转换失败

标签 swift casting

我遇到了非常奇怪的行为,我真的无法理解它的正反面。我正在尝试将类类型存储在数组中并想稍后调用,但它不起作用。这是我的代码

class BaseClass {

    class func getDetails() -> String {
        return "aaaaaa"
    }
}

class Foo: BaseClass {

    override class func getDetails() ->String {
        return "foo"
    }
}


class Bar: BaseClass {
    override class func getDetails() ->String {
        return "bar"
    }
}

var arr = [Foo.self, Bar.self]
func test1 () {

    var x = Foo.self
    println(x.getDetails()) //prints foo
    if let y = arr[0] as? Foo.Type {
        println(y.getDetails()) //doesn't execute

    }
    if let z = arr[0] as? BaseClass.Type {
        println(z.getDetails()) //doesn't execute
    }
    if let t = arr[0] as? BaseClass {
        println(t.dynamicType.getDetails()) //doesn't execute
    }
    // lets crash
    var w = arr[0] as! Foo
    //Could not cast value of type 'Test.Foo' (0x1085f17f0) to 'Test.Foo' (0x1085f1830).

}

我特别疑惑

Could not cast value of type 'Test.Foo' (0x1085f17f0) to 'Test.Foo' (0x1085f1830)

错误。我如何通过向下转换为 BaseClass 来引用数组中的类,以便我可以使用它的 getDetails 函数

最佳答案

嗯...很奇怪。这个

var arr = [Foo.self, Bar.self]
println(arr.count)
println(arr)

将打印 2 然后崩溃,但这工作正常:

var arr: [BaseClass.Type] = [Foo.self, Bar.self]
println(arr.count)
println(arr)

只是您稍后会在代码中收到有关 as? BaseClass.Type 测试总是成功(因此不需要)并且 as? BaseClass 测试总是失败(预期,因为数组的内容不是类的实例,而是它们的类型)。

The Swift Programming Language为类型转换定义类层次结构 部分中引导,我们发现

Swift’s type checker is able to deduce that Movie and Song have a common superclass of MediaItem, and so it infers a type of [MediaItem] for the library array:

let library = [
    Movie(name: "Casablanca", director: "Michael Curtiz"),
    Song(name: "Blue Suede Shoes", artist: "Elvis Presley"),
    Movie(name: "Citizen Kane", director: "Orson Welles"),
    Song(name: "The One And Only", artist: "Chesney Hawkes"),
    Song(name: "Never Gonna Give You Up", artist: "Rick Astley")
]
// the type of "library" is inferred to be [MediaItem]

看起来您正在做类似的事情,所以人们希望它能工作,但您没有 - 您存储的是类的类型,而不是它们的实例。

关于快速向下转换失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29774110/

相关文章:

json - 动态 JSON 解码 Swift 4

Swift - 从另一个没有参数的方法调用@IBAction

ios - 从雅虎天气检索到的 JSON 数据处理错误

casting - Go:在类型开关中将任何 int 值转换为 int64

c - 为什么 signed short 扩展到 4 个字节?

java - 如何将地理点经度+纬度转换为两倍?

typescript - 我可以对 Typescript 中的变量进行类型断言,使其对整个 block /函数有效吗?

c - 将指针转换为 void* 然后与 NULL 进行比较是否安全

ios - Xcode Swift 参数类型不符合预期类型 'Decoder'

ios - SDWebImage 不会在真实设备上显示本地存储的图像,但会显示在模拟器中