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) //未执行
}
热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练