Swift - 类型转换(as as! as?)
2016-12-28 17:13
453 查看
swift 类型转换
一,as
1,as使用场合
(1)从派生类转换为基类,向上转型(upcasts)
(2)消除二义性,数值类型转换
(3)switch 语句中进行模式匹配
如果不知道一个对象是什么类型,你可以通过switch语法检测它的类型,并且尝试在不同的情况下使用对应的类型进行相应的处理。
2,as!使用场合
向下转型(Downcasting)时使用。由于是强制类型转换,如果转换失败会报 runtime 运行错误。
UIButton的点击方法: 确定sender 是个UIBtutton类型
3,as?使用场合
as? 和 as! 操作符的转换规则完全一样。但 as? 如果转换不成功的时候便会返回一个 nil 对象。成功的话返回可选类型值(optional),需要我们拆包使用。
由于 as? 在转换失败的时候也不会出现错误,所以对于如果能确保100%会成功的转换则可使用 as!,否则使用 as?
如下使用如果
一,as
1,as使用场合
(1)从派生类转换为基类,向上转型(upcasts)
class Animal {} class Cat: Animal {} let cat = Cat() let animal = cat as Animal
(2)消除二义性,数值类型转换
let num1 = 42 as CGFloat let num2 = 42 as Int let num3 = 42.5 as Int let num4 = (42 / 2) as Double
(3)switch 语句中进行模式匹配
如果不知道一个对象是什么类型,你可以通过switch语法检测它的类型,并且尝试在不同的情况下使用对应的类型进行相应的处理。
switch animal { case let cat as Cat: print("如果是Cat类型对象,则做相应处理") case let dog as Dog: print("如果是Dog类型对象,则做相应处理") default: break }
2,as!使用场合
向下转型(Downcasting)时使用。由于是强制类型转换,如果转换失败会报 runtime 运行错误。
class Animal {} class Cat: Animal {} let animal :Animal = Cat() let cat = animal as! Cat
UIButton的点击方法: 确定sender 是个UIBtutton类型
@IBAction func onClickBtn(_ sender: Any) { let btn = sender as! UIButton }
3,as?使用场合
as? 和 as! 操作符的转换规则完全一样。但 as? 如果转换不成功的时候便会返回一个 nil 对象。成功的话返回可选类型值(optional),需要我们拆包使用。
由于 as? 在转换失败的时候也不会出现错误,所以对于如果能确保100%会成功的转换则可使用 as!,否则使用 as?
let animal:Animal = Cat() if let cat = animal as? Cat{ print("cat is not nil") } else { print("cat is nil") }
如下使用如果
//as! 强转 确定key 取出来的值就是 String 类型并且有值 let str : String = (UserDefaults.standard.object(forKey: "dfad") as! String) print(str) //as? 转成可选类型 有值的话转成string 没有值的话nil let str1 = UserDefaults.standard.object(forKey: "hahh") as? String print(str1!) //除非特别确定 否者一般不建议强转 建议使用as?
相关文章推荐
- Swift-构造方法
- Swift3 MPMoviePlayerViewController的使用,iOS播放视频
- iOS swift 支持中文斜体的方法 自己整理
- swift 下 String 转 NSdate 相互转化,一些日期相关的总结
- Swift-3.0相对于2.3语法的一些变化
- RxSwift 学习指导索引
- RxSwift
- iOS - Swift 上的NSStringFromClass
- Swift3.0 类和结构体的选择
- Swift3.0 闭包(blcok)的全面介绍及使用
- 用Swift3.0和Java编写生产者消费者模式
- swift学习笔记 - 判断当前运行的系统和平台
- swift学习笔记 - 判断当前运行的系统和平台
- Swift3.0 GCD多线程详解
- Swift学习之集合的reduce 操作详解
- swift init (under constrction)
- swift中的转场动画
- 初探Swift3.0带来的变化汇总
- Swift3.0带来的变化汇总
- Swift 2.3 迁移 Swift 3.0 遇到困难和部分解决方案