http://www.hangge.com/blog/cache/detail_693.html
在Swift中,通常使用is和as操作符来实现类型检查和转换。下面通过样例来演示使用方法,首先定义几个类。
1
2
3
4
5
6
7
8
9
10
11
|
//基类,人类
class
Human
{
}
//男人类
class
Man
:human{
}
//女人类
class
Woman
:human{
}
|
(注意:is也可以用来检查某个类是否遵循了某个协议)
1
2
3
4
5
6
7
8
9
10
11
|
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后面加问号“?”)
1
2
3
4
5
6
7
8
9
10
11
|
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
(
"这是个女人"
)
}
}
|
原文出自: www.hangge.com 转载请保留原文链接: http://www.hangge.com/blog/cache/detail_693.html