首页 > 代码库 > Option可选值可选值(二)
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) {
returnbuildingNubmer
}else {
return nil
}
}
}
//通过供选链接调用属性
let john =Person()
iflet 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.")
}
//使用供选链接调用角标
iflet firstRoomName =john.residence?[0].name {
println("The first room name is\(firstRoomName).")
}else {
println("Unable to retrieve the first room name.")
}
Option可选值可选值(二)