首页 > 代码库 > Option可选值(一)
Option可选值(一)
//: Playground - noun: a place where people can play
import Cocoa
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?
}
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) {
returnbuildingNubmer
}else {
return nil
}
}
}
let john =Person()
//let johnsHouse = Residence()
//johnsHouse.rooms[0] = Room(name: "Living Room")
//john.residence = johnsHouse
/*
你能够将多层供选链接连接在一起,能够掘取模型内更下层的属性方法和角标。然而多层供选链接不能再加入比已经返回的供选值很多其它的层。 也就是说:
假设你试图获得类型不是供选类型,因为供选链接它将变成供选类型。假设你试图获得的类型已经是供选类型,因为供选链接它也不会提高供选性。因此:
假设你试图通过供选链接获得 Int 值,不论使用了多少层链接返回的总是 Int?。相似的,假设你试图通过供选链接获得 Int?
值,不论使用了多少层链接返回的总是 Int?。
*/
let johnsAddress =Address()
johnsAddress.buildingName ="The"
johnsAddress.street ="Laurel"
john.residence!.address =johnsAddress
//链接供选返回值的方法
//if let buildingIdentifier = john.residence?
.address?.buildingIdentifier()?
.uppercaseString {
// println("John‘s building identifier is \(buildingIdentifier).")
//}
//连接多层链接
//if let johnsStreet = john.residence?.address?.street {
// println("John‘s street name is \(johnsStreet).")
//} else {
// println("Unable to retrieve the address.")
//}
//使用供选链接调用角标
//if let firstRoomName = john.residence?[0].name {
// println("The first room name is \(firstRoomName).")
//} else {
// println("Unable to retrieve the first room name.")
//}
Option可选值(一)