class Student {
var hobby: Hobby?
}
class Hobby {
var run = "run"
}
//创建了一个新的Student实例,它的hobby属性由于是是可选型而将初始化为nil
let stu = Student()
//如果使用叹号`!`强制展开获得这个stu的hobby属性中的run值,会触发运行时错误,因为这时run没有可以展开的值
let hobby = stu.hobby!.run //运行时错误
//stu.hobby为非nil值的时候,上面的调用会成功,并且把run设置为String类型
let hobby =stu.hobby?. run //无报错
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
}
}
//此方法未指定返回类型,没有返回类型的函数和方法具有隐式返回类型Void,返回值可以是()或空元组。
func printNumberOfRooms() {
print("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 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
}
}
}
读取属性 由于john.residence是nil,这种可选链式调用会失败
let john = Person()
if let roomCount = john.residence?.numberOfRooms {
print("John's residence has \(roomCount) room(s).")
} else {
print("Unable to retrieve the number of rooms.")
}
//Unable to retrieve the number of rooms.
设置属性 通过john.residence来设定address属性也会失败,因为john.residence当前为nil
let someAddress = Address()
someAddress.buildingNumber = "29"
someAddress.street = "Acacia Road"
john.residence?.address = someAddress
let john = Person()
if john.residence?.printNumberOfRooms() != nil {
print("It was possible to print the number of rooms.")
} else {
print("It was not possible to print the number of rooms.")
}
//It was not possible to print the number of rooms.
let john = Person()
if let firstRoomName = john.residence?[0].name {
print("The first room name is \(firstRoomName).")
} else {
print("Unable to retrieve the first room name.")
}
//Unable to retrieve the first room name.