搭配型別.self 和 string interpolation,安全得到型別字串

開發 iOS App 時,有時我們需要輸入跟型別名一樣的字串,比方 cell 的 ID,controller 的 Storyboard ID 等。然而只要是手動輸入字串,就有打錯的可能。

若能搭配型別.self 和 string interpolation,讓 Xcode 的自動完成幫我們輸入,我們將能安全得到型別的字串,不再擔心打錯。比方 "\(Int.self)" 將產生字串 Int。

接下來,我們就以 cell ID 為例,假設 cell ID 和 cell 的類別 SongTableViewCell 同名。

傳統比較不安全的寫法如下,我們手動輸入 "SongTableViewCell"

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {   let cell = tableView.dequeueReusableCell(withIdentifier: "SongTableViewCell", for: indexPath)   return cell}

比較安全的寫法如下。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {   let cell = tableView.dequeueReusableCell(withIdentifier: "\(SongTableViewCell.self)", for: indexPath)   return cell}

我們結合型別.self 和 string interpolation,輸入"\(SongTableViewCell.self)",產生字串 SongTableViewCell。

在 \() 裡輸入 son 後即可選擇 SongTableViewCell

--

--

彼得潘的 iOS App Neverland
彼得潘的 Swift iOS App 開發問題解答集

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com