Option可选值可选值

Posted wzzkaifa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Option可选值可选值相关的知识,希望对你有一定的参考价值。

//: Playground - noun: a place where people can play


import Cocoa


var str1 = "供选链接和强制拆包的不同。

"

class Person {

    var residence: Residence?//供选连接

}

class Residence {

    var rooms = [Room]()

    var numberOfRooms: Int {

        return rooms.count

    }

    subscript(i: Int) -> Room {

        return rooms[i]

    }

    

    func printNumberOfRooms() {

        println("The number of rooms is \(numberOfRooms)")

    }

    

    var address: Address?

}

//假设你创建一个新的 Person 实例,它的 residence 属性因为是被定义为供选的,此属性将默认初始化为空:

//let john = Person()

/*

假设你想使用声明符!强制拆包获得这个人 residence 属性 numberOfRooms 属性值,将会引发执行时错误,由于这时没有能够供拆包的 residence 值。

*/

//let roomCount = john.residence!.numberOfRooms

//供选链接提供了一种还有一种获得 numberOfRooms 的方法。利用供选链接,使用问号来取代原来!的位置:

//let roomCount = john.residence?

.numberOfRooms

/*

if let roomCount = john.residence?.numberOfRooms {

    println("john‘s residence has \(roomCount) room(s).")

} else {

    println("Unable to retrieve the of rooms.")

}


john.residence = Residence()

if let roomCount = john.residence?

.numberOfRooms {

    println("john‘s residence has \(roomCount) room(s).")

} else {

    println("Unable to retrieve the of rooms.")

}*/

/*

为供选链接定义模型类

这些类是由上面的 Person Residence 模型通过加入一个 Room 和一个 Address 类拓展来。

*/

class Room {

    let name: String

    init(name: String) {

        self.name = name

    }

}

class Address {

    var buildingName: String?

    var buildingNubmer: String?

    var street: String?

    

    func buildingIdentifier() -> String? {

        if (buildingName != nil) {

            return buildingName

        } else if (buildingNubmer != nil) {

            return buildingNubmer

        } else {

            return nil

        }

    }

}

//通过供选链接调用属性

let john = Person()

if let roomCount = john.residence?.numberOfRooms {

    println("John‘s residence has \(roomCount) room(s).")

} else {

    println("Unable to retrieve the number of rooms.")

}

//通过供选链接调用方法

var uu = 9

if(john.residence?.printNumberOfRooms() != nil) {

    println("It was possible to print the number of rooms.")

} else {

    println("It was not possible to print the number of rooms.")

}

//使用供选链接调用角标

if let firstRoomName = john.residence?[0].name {

    println("The first room name is \(firstRoomName).")

} else {

    println("Unable to retrieve the first room name.")

}




























以上是关于Option可选值可选值的主要内容,如果未能解决你的问题,请参考以下文章

Option可选值

组成必需值和可选值的期货

用返回非可选值的计算属性覆盖返回可选值的计算属性

excel 设置 单元格的值为可选值,可选值设置为某一列。

Swift 中的可选值是啥?

可选值是啥意思?