Swift4 基礎(chǔ)部分: Optional Chaining(可選鏈)

本文是學(xué)習(xí)《The Swift Programming Language》整理的相關(guān)隨筆属划,基本的語法不作介紹雀哨,主要介紹Swift中的一些特性或者與OC差異點(diǎn)埋凯。

系列文章:

可選鏈可替代強(qiáng)制解析(Optional Chaining as an Alternative to Forced Unwrapping)

You specify optional chaining by placing a question mark 
(?) after the optional value on which you wish to call a 
property, method or subscript if the optional is non-nil. 
This is very similar to placing an exclamation mark (!) 
after an optional value to force the unwrapping of its 
value. The main difference is that optional chaining fails 
gracefully when the optional is nil, whereas forced 
unwrapping triggers a runtime error when the optional is 
nil.
  • 在想調(diào)用的屬性锅减、方法脆诉、或下標(biāo)腳本的可選值后面放一個?甚亭,可以定義一個可選鏈。這很像在可選值后面放一個!來強(qiáng)制拆得其封包內(nèi)的值击胜。它們的主要的區(qū)別在于當(dāng)可選值為空時可選鏈即刻失敗亏狰,然而一般的強(qiáng)制解析將會引發(fā)運(yùn)行時錯誤。

例子:

class Residence {
    var numberOfRooms = 1;
}

class Person {
    var residence: Residence?;
}
let john = Person();
let rootCount = john.residence!.numberOfRooms;

執(zhí)行結(jié)果:

fatal error: unexpectedly found nil while unwrapping an Optional value

我們改寫成可選鏈的方式去訪問numberOfRooms:

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.");
}

執(zhí)行結(jié)果:

Unable to retrieve the number of rooms.

通過可選鏈調(diào)用屬性(Accessing Properties Through Optional Chaining)

例子:

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() {
        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) {
            return buildingNumber;
        } else {
            return 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.");
}

john.residence = Residence();
if let roomCount = john.residence?.numberOfRooms {
    print("John's residence has \(roomCount) room(s).");
} else {
    print("Unable to retrieve the number of rooms.");
}

執(zhí)行結(jié)果:

Unable to retrieve the number of rooms.
John's residence has 0 room(s).

通過可選鏈調(diào)用方法(Calling Methods Through Optional Chaining)

You can use optional chaining to call a method on an optional value, 
and to check whether that method call is successful. You can do this 
even if that method does not define a return value.
  • 可以使用可選鏈來調(diào)用方法去判斷是否方法調(diào)用成功偶摔。即使該方法沒有返回值暇唾。

例子:

let john = Person();
john.residence = Residence();
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.")
}

執(zhí)行結(jié)果:

It was possible to print the number of rooms.

使用可選鏈調(diào)用下標(biāo)腳本(Accessing Subscripts Through Optional Chaining)

You can use optional chaining to try to retrieve and set a value from a 
subscript on an optional value, and to check whether that subscript 
call is successful.
  • 可以使用可選鏈嘗試從下標(biāo)腳本獲取值并且檢查是否調(diào)用成功。

例子:

let john = Person();
john.residence = Residence();
let room:Room = Room(name:"xz");
john.residence?.rooms.append(room);
if let firstRoomName = john.residence?[0].name {
    print("The first room name is \(firstRoomName).")
} else {
    print("Unable to retrieve the first room name.")
}

執(zhí)行結(jié)果:

The first room name is xz.

連接多層鏈接(Linking Multiple Levels of Chaining)

You can link together multiple levels of optional chaining to drill 
down to properties, methods, and subscripts deeper within a model. 
However, multiple levels of optional chaining do not add more levels of 
optionality to the returned value.
  • 可以將多層可選鏈連接在一起啰挪,可以掘取模型內(nèi)更下層的屬性方法和下標(biāo)腳本信不。然而多層可選鏈不能再添加比已經(jīng)返回的可選值更多的層。

例子:

let john = Person();
john.residence = Residence();
john.residence?.address = Address();
john.residence?.address?.street = "beijing road";
if let johnsStreet = john.residence?.address?.street {
    print("John's street name is \(johnsStreet).");
} else {
    print("Unable to retrieve the address.");
}

執(zhí)行結(jié)果:

John's street name is beijing road.

鏈接可選返回值的方法(Chaining on Methods with Optional Return Values)

例子:

let john = Person();
john.residence = Residence();
john.residence?.address = Address();
john.residence?.address?.street = "beijing road";
john.residence?.address?.buildingName = "beijing building";

if let buildingIdentifier = john.residence?.address?.buildingIdentifier()?.uppercased() {
    print("John's building identifier is \(buildingIdentifier).");
}

執(zhí)行結(jié)果:

John's building identifier is BEIJING BUILDING.
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末亡呵,一起剝皮案震驚了整個濱河市抽活,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌锰什,老刑警劉巖下硕,帶你破解...
    沈念sama閱讀 221,888評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異汁胆,居然都是意外死亡梭姓,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,677評論 3 399
  • 文/潘曉璐 我一進(jìn)店門嫩码,熙熙樓的掌柜王于貴愁眉苦臉地迎上來誉尖,“玉大人,你說我怎么就攤上這事铸题≌∷。” “怎么了?”我有些...
    開封第一講書人閱讀 168,386評論 0 360
  • 文/不壞的土叔 我叫張陵丢间,是天一觀的道長探熔。 經(jīng)常有香客問我,道長烘挫,這世上最難降的妖魔是什么诀艰? 我笑而不...
    開封第一講書人閱讀 59,726評論 1 297
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上其垄,老公的妹妹穿的比我還像新娘苛蒲。我一直安慰自己,他們只是感情好捉捅,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,729評論 6 397
  • 文/花漫 我一把揭開白布撤防。 她就那樣靜靜地躺著虽风,像睡著了一般棒口。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上辜膝,一...
    開封第一講書人閱讀 52,337評論 1 310
  • 那天无牵,我揣著相機(jī)與錄音,去河邊找鬼厂抖。 笑死茎毁,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的忱辅。 我是一名探鬼主播七蜘,決...
    沈念sama閱讀 40,902評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼墙懂!你這毒婦竟也來了橡卤?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,807評論 0 276
  • 序言:老撾萬榮一對情侶失蹤损搬,失蹤者是張志新(化名)和其女友劉穎碧库,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體巧勤,經(jīng)...
    沈念sama閱讀 46,349評論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡嵌灰,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,439評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了颅悉。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片沽瞭。...
    茶點(diǎn)故事閱讀 40,567評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖剩瓶,靈堂內(nèi)的尸體忽然破棺而出驹溃,到底是詐尸還是另有隱情,我是刑警寧澤儒搭,帶...
    沈念sama閱讀 36,242評論 5 350
  • 正文 年R本政府宣布吠架,位于F島的核電站,受9級特大地震影響搂鲫,放射性物質(zhì)發(fā)生泄漏傍药。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,933評論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望拐辽。 院中可真熱鬧拣挪,春花似錦、人聲如沸俱诸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,420評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽睁搭。三九已至赶诊,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間园骆,已是汗流浹背舔痪。 一陣腳步聲響...
    開封第一講書人閱讀 33,531評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留锌唾,地道東北人锄码。 一個月前我還...
    沈念sama閱讀 48,995評論 3 377
  • 正文 我出身青樓,卻偏偏與公主長得像晌涕,于是被迫代替她去往敵國和親滋捶。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,585評論 2 359

推薦閱讀更多精彩內(nèi)容