Swift垂头丧气
例子
可以使用类型转换运算符as?,和将变量向下转换为子类型as!。
该as?运营商尝试投射到一个亚型。
它可能会失败,因此它返回一个可选的。
let value: Any = "John"
let name = value as? String
print(name) // prints Optional("John")
let age = value as? Double
print(age) //打印零该as!运营商强制铸造。
它不返回可选项,但如果转换失败则会崩溃。
let value: Any = "Paul" let name = value as! String print(name) // prints "Paul" let age = value as! Double // crash: "Could not cast value…"
将类型转换运算符与条件展开一起使用是很常见的:
let value: Any = "George"
if let name = value as? String {
print(name) // prints "George"
}
if let age = value as? Double {
print(age) //未执行
}
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短