作者:Natasha,原文鏈接,原文日期:2016-04-09
譯者:Crystal Sun;校對:小鍋;定稿:shanks
我還在習(xí)慣 Swift 中的關(guān)聯(lián)類型(Associated Type),盡管它們已經(jīng)出現(xiàn)好一陣子了,我最初是從這篇文章 @alexisgallagher里開始理解它們的。
我很開心昨天能在 iOS 開發(fā)中用它們解決 iOS 開發(fā)中的一個常見問題:在 Swift 中對使用 Storyboard 和 Segue 的 View Controller 進(jìn)行依賴注入。
昨天我更新了博客,但是我的協(xié)議一開始看起來是這樣的:
protocol Injectable {
associatedType T
func inject(thing: T)
func assertDependencies()
}
注意 thing 這個參數(shù)!因為每個 View Controller 都會被注入一些特別具體的東西 —— 有可能是基于文本的、基于數(shù)值的、基于數(shù)組的,或者其他任何類型!我不知道如何更好地對參數(shù)命名。所以 thing 看起來是最合適的參數(shù)名字了。
實(shí)現(xiàn)看起來是這樣子的:
func inject(thing: T) {
textDependency = thing
}
我實(shí)在不喜歡 thing 這個名字 —— 完全沒有可讀性。所以今天早上,我想到了一個瘋狂的解決方案,不用 thing 了,結(jié)果這方法竟然走得通!
protocol Injectable {
associatedType T
// 用 _ 替換掉 thing
func inject(_: T)
}
替換掉 thing,我在協(xié)議里把參數(shù)名字留空(即改成 _)!
很明顯,現(xiàn)在實(shí)現(xiàn)此協(xié)議時,我可以把參數(shù)命名成任何名字了。
class MyStringDependencyViewController: UIViewController, Injectable {
private var textDependency: String!
// 在這個地方,thing 是 text
func inject(text: String) {
textDependency = text
}
}
class MyIntDependencyViewController: UIViewController, Injectable {
private var numberDependency: Int!
// 在這個地方,thing 是 number
func inject(number: Int) {
numberDependency = number
}
}
現(xiàn)在,實(shí)現(xiàn)過程非常清晰,隨著使用關(guān)聯(lián)類型的次數(shù)增多,我越來越喜歡它了。
本文由 SwiftGG 翻譯組翻譯,已經(jīng)獲得作者翻譯授權(quán),最新文章請訪問 http://swift.gg。