发布于 2015-06-14 01:49:20 | 115 次阅读 | 评论: 0 | 来源: 网络整理

类型转换运算符(Type-Casting Operators)

有两种类型转换操作符: as 和 is. 它们有如下的形式:

expression as type
expression as? type
expression is type

as 运算符会把目标表达式转换成指定的类型(specified type),过程如下:

  • 如果类型转换成功, 那么目标表达式就会返回指定类型的实例(instance). 例如:把子类(subclass)变成父类(superclass)时.
  • 如果转换失败,则会抛出编译错误( compile-time error)。
  • 如 果上述两个情况都不是(也就是说,编译器在编译时期无法确定转换能否成功,) 那么目标表达式就会变成指定的类型的optional. (is an optional of the specified type ) 然后在运行时,如果转换成功, 目标表达式就会作为 optional的一部分来返回, 否则,目标表达式返回nil. 对应的例子是: 把一个 superclass 转换成一个 subclass.

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 ? 可选 类型
 

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务