Swift:使協議中的關聯類型參數可讀

做者:Natasha,原文連接,原文日期:2016-04-09
譯者:Crystal Sun;校對:小鍋;定稿:shanksswift

我還在習慣 Swift 中的關聯類型(Associated Type),儘管它們已經出現好一陣子了,我最初是從這篇文章 @alexisgallagher裏開始理解它們的。 數組

我很開心昨天能在 iOS 開發中用它們解決 iOS 開發中的一個常見問題:在 Swift 中對使用 Storyboard 和 Segue 的 View Controller 進行依賴注入ui

昨天我更新了博客,可是個人協議一開始看起來是這樣的:翻譯

protocol Injectable {
    
    associatedType T
    func inject(thing: T)
    func assertDependencies()
}

注意 thing 這個參數!由於每一個 View Controller 都會被注入一些特別具體的東西 —— 有多是基於文本的、基於數值的、基於數組的,或者其餘任何類型!我不知道如何更好地對參數命名。因此 thing 看起來是最合適的參數名字了。code

實現看起來是這樣子的:ci

func inject(thing: T) {
    textDependency = thing
}

我實在不喜歡 thing 這個名字 —— 徹底沒有可讀性。因此今天早上,我想到了一個瘋狂的解決方案,不用 thing 了,結果這方法居然走得通!開發

protocol Injectable {
    associatedType T
    
    // 用 _ 替換掉 thing
    func inject(_: T)
    
}

替換掉 thing,我在協議裏把參數名字留空(即改爲 _)!
很明顯,如今實現此協議時,我能夠把參數命名成任何名字了。get

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
    }
}

如今,實現過程很是清晰,隨着使用關聯類型的次數增多,我愈來愈喜歡它了。博客

本文由 SwiftGG 翻譯組翻譯,已經得到做者翻譯受權,最新文章請訪問 http://swift.ggit

相關文章
相關標籤/搜索