class ClassA {
var name:String
init(name:String) {
self.name = name
}
}
class ClassB: ClassA {
var describe:String
init(name: String, describe:String) {
self.describe = describe
super.init(name: name)
}
}
class ClassC: ClassA {
var type:String
init(name:String, type:String) {
self.type = type
super.init(name: name)
}
}
let arr = [ClassB.init(name: "B0", describe: "B0 describe"),
ClassC.init(name: "C0", type: "C0 type"),
ClassB.init(name: "B1", describe: "B1 describe"),
ClassC.init(name: "C1", type: "C1 type"),
ClassC.init(name: "C2", type: "C2 type")]
is
:检查一个实例是否属于某类型let v = arr[1]
if v is ClassB{
print("ClassB")
}else{
print("other")
}
//ClassB
as
**: 子类转父类(向上转型)let v0 = arr[0] as ClassA
print(v0) //ClassB
as?
:当你不确定父类转子类(向下转型)可以成功时,用类型转换的条件形式as?
,返回一个可选值,若下转是不可能的,可选值将是nil
let v1 = arr[0] as? ClassC
print(v1) // nil
as!
:可以确定向下转型一定会成功时,才使用强制形式as!
,向下转型为一个不正确的类型时,强制形式的类型转换会触发一个运行时错误let v2 = arr[0] as! ClassB
print(v2) //ClassB
任何类型
,包括函数类型任何类类型的实例
示例var things = [Any]()
things.append(0)
things.append(0.0)
things.append(42)
things.append(3.14159)
things.append("hello")
things.append((3.0, 5.0))
things.append({ (name: String) -> String in "Hello, \(name)" })
如果你确实想使用Any类型来承载可选值,你可以使用as操作符显式转换为Any
var things = [Any]()
let value:Int? = 3
things.append(value) //有警告
things.append(value as Any) //无警告