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