在Swift中,通常使用is和as操作符来实现类型检查和转换。下面通过样例来演示使用方法,首先定义几个类。
原文出自:www.hangge.com 转载请保留原文链接:http://www.hangge.com/blog/cache/detail_693.html
//基类,人类
class Human{
}
//男人类
class Man:human{
}
//女人类
class Woman:human{
}
1. is 用来做类型检查
(注意:is也可以用来检查某个类是否遵循了某个协议)
let man = Man()
let woman = Woman()
var arr = [man,woman]
for people in arr {
if people is Man {
println("这是个男人")
}else if people is Woman {
println("这是个女人")
}
}
2. as 用来做类型转换
(注意:如果不确定类型转换能否成功,可以在as后面加问号“?”)
let man = Man()
let woman = Woman()
var arr = [man,woman]
for people in arr {
if let m = people as? Man {
println("这是个男人")
}else if let w = people as? Woman {
println("这是个女人")
}
}