as、as!、as? 這三種類型轉換操作符的異同,以及各自的使用場景。
1,as使用場合
(1)從派生類轉換為基類,向上轉型(upcasts)
1
2
3
4
|
class
Animal
{}
class
Cat
:
Animal
{}
let
cat =
Cat
()
let
animal = cat
as
Animal
|
1
2
3
4
|
let
num1 = 42
as
CGFloat
let
num2 = 42
as
Int
let
num3 = 42.5
as
Int
let
num4 = (42 / 2)
as
Double
|
如果不知道一個對象是什么類型,你可以通過switch語法檢測它的類型,並且嘗試在不同的情況下使用對應的類型進行相應的處理。
1
2
3
4
5
6
7
|
switch
animal {
case
let
cat
as
Cat
:
print
(
"如果是Cat類型對象,則做相應處理"
)
case
let
dog
as
Dog
:
print
(
"如果是Dog類型對象,則做相應處理"
)
default
:
break
}
|
向下轉型(Downcasting)時使用。由於是強制類型轉換,如果轉換失敗會報 runtime 運行錯誤。
1
2
3
4
|
class
Animal
{}
class
Cat
:
Animal
{}
let
animal :
Animal
=
Cat
()
let
cat = animal
as
!
Cat
|
3,as?使用場合
as? 和 as! 操作符的轉換規則完全一樣。但 as? 如果轉換不成功的時候便會返回一個 nil 對象。成功的話返回可選類型值(optional),需要我們拆包使用。
由於 as? 在轉換失敗的時候也不會出現錯誤,所以對於如果能確保100%會成功的轉換則可使用 as!,否則使用 as?
1
2
3
4
5
6
7
|
let
animal:
Animal
=
Cat
()
if
let
cat = animal
as
?
Cat
{
print
(
"cat is not nil"
)
}
else
{
print
(
"cat is nil"
)
}
|