Swift学习09:swift中as、as!、as?号的使用
关于 as
1 2 3 4
| class Auto {} class Car : Auto {} let car = Car() let truck = car as Auto
|
1 2 3 4 5 6 7
| swich Auto { case let car as Car: print("这里是Car类型对象"); case let truck as Truck: print("这里是Truck类型对象"); default: break }
|
as!
向下强制类型转换,如果转换失败会报错
1 2 3 4
| class Auto {} class Car: Auto {} let auto: Auto = Car() let car = auto as! Car
|
as?
向下强制类型转换,如果转换失败会返回nil
1 2 3 4 5 6 7
| let auto: Auto = Car() if let car = auto as? Car { print("这是Car") } else { print("这不是Car") }
|
- Post title:Swift学习09:swift中as、as!、as?号的使用
- Post author:张建
- Create time:2023-02-03 19:27:15
-
Post link:https://redefine.ohevan.com/2023/02/03/Swift/Swift学习09:swift中as、as!、as?号的使用/
-
Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.