美文网首页
swift中as/as?/as! 的区别和使用

swift中as/as?/as! 的区别和使用

作者: 柚子皮肤 | 来源:发表于2017-11-20 18:15 被阅读0次

    1.as

    (1)从派生类转换成基类,(upcasts)向上转换,即:子类向父类转换.

    定义一个父类People

    class People : NSObject {

     var name : String

     init(_ name : String) { 

     self.name = name

     }

     }

    定义子类:

     class Teacher : People {

     }

     class Student : People {

     } 

    //展示名字

    func showName(_ people : People) {

    print("The name is \(people.name)")

    }

    //实例化

    let tea = Teacher("Mr.Li")

    let stu = Student("Tom")

    let people_1 = tea as People

    let people_2 = stu as People

    showName(people_1)

    showName(people_2)

    打印结果:

    可以看到子类转换成父类了

    (2)消除二义性,数值类型转换.

    let age = 22 as Int //22.5 as Int 编译器会自动报错,因为Double不能直接转成Int,不向低范围转换.

    let height = 161 as CGFloat

    let money = (50/2) as Double

    print("age = \(age),height = \(height),money = \(money)")

    打印结果:

    (3)switch 语句中进行模式匹配.通过switch语法检测对象的类型,根据对象类型进行处理。

    switch people_1 {

    case _ as Student:

    print("是Student类型,打印学生成绩单...")

    case _ as Teacher:

    print("是Teacher类型,打印老师工资单...")

    default:

    break

    }

    打印结果:

    2. as!

    向下转型(Downcasting)时使用。由于是强制类型转换,如果转换失败会报 runtime 运行错误。

    let people_3 : People = Student("蒙奇_D_路飞")

    let people_4 = people_3 as! Student

    print("这个人的名字是:\(people_4.name)")

    print("people3的类型是:\(people_3.self). people4的类型是:\(people_4.self)")

    打印结果:

    3. as?

    跟as!转换一样,区别是as?转换不成功时会返回nil对象,不会报错. 转换成功时返回的是可选类型.

    所以:如果可以确定100%能转换成功就使用as!, 否则使用as?

    if let someone = people_3 as? Teacher {//if 条件语句里定义的变量,作用域只有在紧跟着它的那句语句里才有用.(swift4.0)

    print("\(someone.name) is a student")

    }else{

    //这里 someone不能使用,使用时编译报错:没有定义.

    print("someone is not a student")

    }

    打印结果:

    这里people_3是Student类型,转Teacher类型失败,返回nil对象,所以打印走的是else语句.

    相关文章

      网友评论

          本文标题:swift中as/as?/as! 的区别和使用

          本文链接:https://www.haomeiwen.com/subject/rouvvxtx.html