发布于 2015-06-14 01:49:20 | 121 次阅读 | 评论: 0 | 来源: 网络整理
有两种类型转换操作符: as 和 is. 它们有如下的形式:
expression
astype
expression
as?type
expression
istype
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 ? 可选 类型