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 60岁长辈祝福语简短
13 祝福语老人简短话语
14 生物老师英语祝福语简短
15 叶海燕老师祝福语简短
16 老师高考后祝福语 简短
17 年后祝福语简短走心
18 梳子结婚蛋糕祝福语简短