is & as
是用于swift 的类型检测
用简单的话来说就是:
is 是判断某个实例是否是某种类型的子类型
as 用于类型转换, 将父类类型的实例转换成子类类型,as? 试图向下转换,如果不能成功则返回nil
as!试图向下转换,并强制解包
class FatherClass {
var name: String
init(name: String) {
self.name = name
}
}
class SubClassA: FatherClass {
var proA: String
init(name: String,proA: String) {
self.proA = proA
super.init(name: name)
}
}
class SubClassB: FatherClass {
var proB: String
init(name: String,proB: String) {
self.proB = proB
super.init(name: name)
}
}
let dic = [
SubClassA(name: "One",proA: "A pro one"),SubClassA(name: "Two",proA: "A pro two"),SubClassB(name: "Three",proB: "B pro one"),SubClassA(name: "Four",proA: "A pro three"),SubClassA(name: "Five",proA: "A pro four")
]
for item in dic {
if item is SubClassA {
print("\(item.name) is SubClassA")
} else if item is SubClassB {
print("\(item.name) is SubClassB")
}
}
//One is SubClassA
//Two is SubClassA
//Three is SubClassB
//Four is SubClassA
//Five is SubClassA
for item in dic {
if let subClassA = item as? SubClassA {
print("SubClassA: '\(subClassA.name)',proA. \(subClassA.proA)")
} else if let subClassB = item as? SubClassB {
print("SubClassB: '\(subClassB.name)',proB. \(subClassB.proB)")
}
}
//SubClassA: 'One',proA. A pro one
//SubClassA: 'Two',proA. A pro two
//SubClassB: 'Three',proB. B pro one
//SubClassA: 'Four',proA. A pro three
//SubClassA: 'Five',proA. A pro four
Any & AnyObject
两种不确定类型
AnyObject可以代表任何class类型的实例。
Any可以表示任何类型,除了方法类型(function types)。
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(SubClassA(name: "Six",proA: "A pro five"))
things.append(SubClassB(name: "Seven",proB: "B pro two"))
for thing in things {
switch thing {
case 0 as Int:
print("zero as an Int")
case 0 as Double:
print("zero as a Double")
case let someInt as Int:
print("an integer value of \(someInt)")
case let someDouble as Double where someDouble > 0:
print("a positive double value of \(someDouble)")
case is Double:
print("some other double value that I don't want to print")
case let someString as String:
print("a string value of \"\(someString)\"")
case let (x,y) as (Double,Double):
print("an (x,y) point at \(x),\(y)")
case let subClassA as SubClassA:
print("a subclass called '\(subClassA.name)',proA. \(subClassA.proA)")
case let subClassB as SubClassB:
print("a subclass called '\(subClassB.name)',proB. \(subClassB.proB)")
default:
print("something else")
}
}
//zero as an Int
//zero as a Double
//an integer value of 42
//a positive double value of 3.14159
//a string value of "hello"
//an (x,y) point at 3.0,5.0
//a subclass called 'Six',proA. A pro five
//a subclass called 'Seven',proB. B pro two
⚠️注意:在一个switch语句的case中使用强制形式的类型检查操作符(as,而不是 as?)来检查和转换到一个明确的类型。在 switch case 语句的内容中这种检查总是安全的。