强制解析!可选类型会引起运行时错误。采用可选?来解析,可选链是一个链式访问,逐层访问。
class Person {
var residence: Residence?
}
class Residence {
var rooms = [Room]()
var numberOfRooms: Int {
return rooms.count
}
subscript(i: Int) -> Room {
get {
return rooms[i]
}
set {
rooms[i] = newValue
}
}
func printNumberOfRooms() {
print("The number of rooms is \(rooms.count)")
}
var address: Address?
}
class Room {
var name: String
init(name: String) {
self.name = name
}
}
class Address {
var buildingName: String?
var buildingNumber: String?
var street: String?
func buildingIdentifier() -> String? {
if buildingName != nil {
return buildingName
} else if buildingNumber != nil && street != nil {
return "\(buildingNumber) \(street)"
} else {
return nil
}
}
}
let john = Person()
if let residence = john.residence {
print(residence.printNumberOfRooms())
}
if let address = john.residence?.address {
if let addressID = address.buildingIdentifier() {
print(addressID)
} else {
print("Unable to retrieve address identifier")
}
} else {
print("Unable to retrieve the address.")
}
john.residence = Residence()
if let residence = john.residence {
print(residence.printNumberOfRooms())
}
if let address = john.residence?.address {
if let addressID = address.buildingIdentifier() {
print(addressID)
} else {
print("Unable to retrieve address identifier")
}
} else {
print("Unable to retrieve the address.")
}
john.residence?.address = Address()
john.residence?.address?.buildingName = "AiDing Dasha"
if let building = john.residence?.address?.buildingIdentifier() {
print(building)
}
john.residence?.rooms.append(Room(name: "Room 1001"))
john.residence?.rooms.append(Room(name: "Room 1002"))
john.residence?[0] = Room(name: "Room 2001")
if let room = john.residence?[0] {
print(room.name)
}