Skip to main content

[Swift3] ? 與 !

學習 Swift 語言覺得最有趣就是變數後面的問號與驚嘆號。看著程式碼帶著一堆 ??!! 相信初學的朋友應該都挺傻眼的。其實會出現 ? 與 ! 是因為 Swift runtime 的特性:不容許變數有 nil 的存在而產生的,這時候就需要先來學習什麼是變數為 Optional(可選性)。

以下是一般情況,預先宣告了一個沒有賦值的變數,然後不小心先使用它,這種情況下就會出現 runtime error:

var string: String
print(string)

---output---------
variable 'string' used before being initialized

加上?宣告成 Optional 就安全過關:

var string: String? //-> 設定為 Optional 所以 runtime safe
print(string)

---output---------
nil

重點一:變數會有 nil 情況發生就是加上 ?

class ClassA {
var b: ClassB? // 不確定b 會不會存在,加上? 就不需要在 init 初始化
}

class ClassB {
var count = 1
var string = "Hahaha"
var x = 12.0
var y = 20.5
}

因為使用了問號 b 還是 Optional,所以沒有 runtime error。

let a = ClassA()
print( "\(a.b?.count)" )

---output---------
nil


而與 ? 相對的就是 ! , 一個包裝,一個拆包。驚嘆號最大的作用就是將「虛轉成實」,所以當使用!打開 Optional 變數時,如果該變數還是 nil 的話,就會出現 runtime error。

let a = ClassA()
print( "\(a.b!.count)" )
//使用 ! 強制將 Optional 的 b 打開,結果因為 b 是 nil 所以有 runtime error

---output---------
fatal error: unexpectedly found nil while unwrapping an Optional value

重點二:想要使用 ! 強制拆包,就必須要很肯定該包裝的內容物是存在的。

Optional Chaining (可選鍵鏈)

Optional 變數可以直接串連取用,由左至右當某一層為 nil 時,就會停止串連。

class ClassC {
var d: ClassD?
}

class ClassD {
var string: String?
}

let obj1 = ClassC()
print("\(obj1.d?.string?.characters.count)")

let obj2 = ClassC()
obj2.d = ClassD()
obj2.d?.string = "I have value."
print("\(obj2.d?.string?.characters.count)")

---output-------
nil
Optional(13)

重點三:透過 Optional Chaining 可以取用多層級下的變數值

If let 與 guard 判斷式

續上段,當我們使用 Optional Chaining 時,為了判斷該變數值存不存在,會使用 if let 將值存到另外一個區域變數內:

let obj3 = ClassC()
obj3.d = ClassD()
obj3.d?.string = "I have value."

if let count = obj3.d?.string?.characters.count {
print("obj3 的字數有: \(count)")
}else{
//值不存在
}

---output-------
obj3 的字數有: 13

雖然 if let 很好用,但是在函式內常使用也可能會陷入 if let {} 的無限迴圈,這時候可以用 guard 敘述讓函式看起來更簡潔,也可以簡略其他不必要的判斷。

guard [condition == true] else {
// if false 就必須馬上跳出
return [函式回傳值]
}

// 上面條件過關,所以繼續執行

例如從網路讀取 JSON string 轉成 struct object, 這時候使用 guard 可以讓 init 建構式清爽又乾淨。

struct Item {
let title: String
let marked : Bool

init?(_ dist: [String: Any]) {
guard let title = dist["title"] as? String,
let marked = dist["marked"] as? Bool
else {
return nil
}

self.title = title
self.marked = marked
}
}


重點四:雖然針對 Optional 變數有很多拆法,但是保持乾淨也是很重要的。

總結

最後直接拿常用的 UITableViewDataSource cellForRowAt 函式來說明三種拆法:
1. 使用 ! 拆包:看起來很乾淨實際危險性高,因為必須確定不會有錯誤發生

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! Cell
cell.textLabel?.text = "Row: \(indexPath.row)"

return cell
}

2. 使用 if let 判斷:安全性夠,但是一旦 cell 需要做很多事情的話,會有很多 {} 包圍

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? Cell {
cell.textLabel?.text = "Row: \(indexPath.row)"
return cell
}else{
return UITableViewCell()
}
}

3. 使用 guard 判斷式: 安全且函式內較乾淨,建議採用

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? Cell else {
return UITableViewCell()
}

cell.textLabel?.text = "Row: \(indexPath.row)"
return cell
}

Comments

Popular posts from this blog

[Swift3] weak 與 unowned 關鍵字

雖然在 Swift 中看起來"很像"是不需要煩惱內存管理的問題,不過實際上它還是遵循著自動引用計數 (ARC) 的規則,當一個物件沒有被其他對象引用時會自動被銷毀,如果三魂七魄沒有完全回位的話,就會有個靈體留在現世的空間裡,最經典的範例如下: 閉包(Closure)引用 classClassA { typealias Complete = ()->() var name : String var onComplete : Complete? init(_ name: String){ self.name = name print("Hello I am \(self.name)") onComplete = { print("\(self.name): onComplete!") // --> 閉包引用 self, 計數 + 1 } } deinit { print("deinit: \(self.name)") } } var a : ClassA? = ClassA("A") // --> 引用計數 + 1 a = nil // 2-1 = 1 還剩下 1 所以沒辦法銷毀 ---output------- Hello I am A 由於這邊的 onComplete 宣告為 Optional, 正確的做法要連同 onComplete 一起刪除才可以被回收,若不是 Optional 則會進入無法回收狀態: var b : ClassA? = ClassA("B") b?.onComplete = nil // --> 還好是 Optional 可以設成 nil 計數 - 1 b = nil // 計數 = 0 所以被回收 ---output------- Hello I am B deinit: B 但是做人不需要煩惱太多,這時候就出動 unowned 關鍵字讓物件可以順利被回收: onComplete = { [unowned self] in print...

Robotlegs AS3 MVC framework in Flex project (I)

由於今天在 奶綠茶的 Robotlegs FlashAS3 MVC framework 看到他讚賞 Robotlegs AS3 MVC framework 的好用,不禁好奇的來研究一番... 其實這個 AS3 MVC framework 出現有些時日,但是一直都沒有特別的關注它。簡單看完 Robotlegs 最佳實踐 ,其實就可以大部分的了解 Robotlegs 運作的邏輯。不如其他的 MVC framework 有很多語言版本, Robotlegs 完全是專注在 AS3 上。也由於僅有一個版本,所以訊息傳遞是利用 AS3 Event 機制來完成,對於一些想要入門實作 MVC 的 Flash 工程師來說絕對是比 pureMVC 好入門很多...=) Robotlegs 的重點就是搭著「 依賴注入( Dependency Injection) 」達成 MVCS 的架構,  擷取用最佳實踐的中文翻譯解釋: Quote: 最簡單地, 依賴注入是為對象提供實例變量或屬性的行為. 當你傳遞一個變量到一個類的構造函數, 你在使用依賴注入. 當你設置一個類的屬性, 你在使用依賴注入. 如果你不是使用嚴格的過程或線性方式編寫AS3, 很可能你現在就在使用依賴注入。 呃...依賴注入? ?簡單來講一台霜淇林機,你要賣什麼口味的霜淇林就是依賴不同的原料放置到左右兩個攪拌桶內,而每一個口味可以透過介面實作來達成依賴注入。 以下是簡單的 Dependency Injection 的 Setter injection 範例: public interface 霜淇淋介面 { function 擠():void; } 然後實作: public class 巧克力 implements 霜淇淋介面{ public function 擠():void{ trace("巧克力口味的霜淇淋"); } } public class 草莓 implements 霜淇淋介面{ public function 擠():void{ trace("草莓口味的霜淇淋"); } } public class 香草 implements 霜淇淋介面{ public function 擠():void{ ...