/// 父类 Person
class Person {
var name: String
init(name: String){
self.name = name
}
}
/// 子类 Woman
class Woman: Person {
var female: String
init(name: String, male: String) {
self.female = male
super.init(name: name)
}
}
/// 子类 Man
class Man: Person {
var weight: String
init(name: String, weight: String) {
self.weight = weight
super.init(name: name)
}
}
let arrays = [
Woman(name: "gzz", male: "she"),
Woman(name: "glz", male: "she"),
Man(name: "ty", weight: "180"),
Man(name: "az", weight: "101"),
Man(name: "az", weight: "102")
] /// arrays 的类型被推断为Person
用类型检查操作符(is
)来检查一个实例是否属于特定子类型。若实例属于那个子类型,类型检查操作符返回 true
,否则返回 false
。
下面的例子定义了两个变量,womanCount
和 manCount
,用来计算数组 arrays
中 Woman
和 Man
类型的实例数量:
var womanCount = 0
var manCount = 0
for item in arrays{
if item is Woman{
++womanCount
}
if item is Man{
++manCount
}
}
print("womamCount: \(womanCount)") // 2
print("manCount: \(manCount)") // 3
数组中的每一个 item
可能是 Woman
或 Man
。事前你不知道每个 item
的真实类型,所以使用类型转换(as?
)去检查
for item in arrays{
if let _ = item as? Woman{
print("woman")
//
}
if let _ = item as? Man{
print("man")
//
}
}
Swift
为不确定类型提供了两种特殊的类型别名:
AnyObject
可以表示任何类类型的实例。
Any
可以表示任何类型,包括函数类型。
AnyObject
下面的示例定义了一个 [AnyObject] 类型的数组并填入三个 Man
类型的实例:
let objects: [AnyObject] = [
Man(name: "Xt", weight: "180"),
Man(name: "Xt1", weight: "180"),
Man(name: "Xt2", weight: "180"),
]
因为知道这个数组只包含 Man
实例,你可以直接用(as!
)下转并解包到非可选的 Man
类型
for object in objects{
let man = object as! Man
print("man :‘\(man.name)‘")
}
Any
使用 Any
类型来和混合的不同类型一起工作,包括函数类型和非类类型。它创建了一个可以存储
var things = [Any]()
// 添加
things.append(0)
things.append(3.14159)
things.append("hello")
things.append((3.0, 5.0))
things.append(Man(name: "Xt", weight: "171"))
things.append(Woman(name: "Xt1", male: "ll"))
你可以在 switch
表达式的 case
中使用 is
和 as
操作符来找出只知道是 Any
或 AnyObject
类型的常量或变量的具体类型。下面的示例迭代 things
数组中的每一项,并用 switch
语句查找每一项的类型。有几个 switch
语句的 case
绑定它们匹配到的值到一个指定类型的常量,从而可以打印这些值
for thing in things {
switch thing {
case 0 as Int:
print("zero as an Int")
case let someDouble as Double where someDouble > 0:
print("a positive double value of \(someDouble)")
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 man as Man:
print("Man: \(man.name)")
case let woman as Woman:
print("woman: \(woman.name)")
default:
print("something else")
}
}
Swift 类型转换is, as, Any, AnyObject(十二)
原文:http://blog.csdn.net/sinat_30162391/article/details/51171325