Swift_可选链

Swift_可选链


点击查看源码

//可选链
func test() {
    class Person {
        //可选属性可能为nil或Residence类
        var residence: Residence?
    }
    
    class Residence {
        var numberOfRooms = 1
    }
    
    let john = Person()
    john.residence = Residence()
    
    //可选获得
    var roomCount = john.residence?.numberOfRooms
    
    print(roomCount)
    
    //强制获得
    roomCount = john.residence!.numberOfRooms
    
    print(roomCount)
    
    // if获得
    if let roomCount = john.residence?.numberOfRooms {
        print(roomCount)
    }
    
    /*  print
     
     Optional(1)
     Optional(1)
     1
     
     */
}
posted @ 2017-03-06 09:11  旭宝爱吃鱼  阅读(160)  评论(0编辑  收藏  举报