有兩種類型轉換操作符: as 和 is. 它們有如下的形式:
expressionastype
expressionas?type
expressionistype
as 運算符會把目標表達式轉換成指定的類型(specified type),過程如下:
class SomeSuperType {}
class SomeType: SomeSuperType {}
class SomeChildType: SomeType {}
let s = SomeType()
let x = s as SomeSuperType // known to succeed; type is SomeSuperType
let y = s as Int // known to fail; compile-time error
let z = s as SomeChildType // might fail at runtime; type is SomeChildType?
使用'as'做類型轉換跟正常的類型聲明,對于編譯器來說是一樣的。例如:
let y1 = x as SomeType // Type information from 'as'
let y2: SomeType = x // Type information from an annotation
'is' 運算符在“運行時(runtime)”會做檢查。 成功會返回true, 否則 false
檢查不可為已知為true或false在編譯時。下面是無效的:上述檢查在“編譯時(compile time)”不能使用。 例如下面的使用是錯誤的:
"hello" is String
"hello" is Int
關于類型轉換的更多內容和例子,請參見: Type Casting.
類型轉換運算符(type-casting-operator)語法
類型轉換運算符 → is 類型 | as ? 可選 類型