Swift:协议中关联类型参数可读
2016-04-12 本文已影响402人
sing_crystal
原文链接
原文日期:2016-04-09
译者:Crystal Sun
我慢慢习惯了 Swift 里的 Associated Type,尽管它们已经出现好一阵子了,我最初是从这篇文章 @alexisgallagher里开始理解它们的。
我很开心昨天能在 iOS 开发中用它们解决一些问题:Swift 语言下使用 Storyboard 和 Segue 在 View Controller 里引入数据。
昨天我更新了博客,一开始协议看起来像是这样:
protocol Injectable {
associatedType T
func inject(thing: T)
func assertDependencies()
}
注意 thing!因为每个 View Controller 都会被注入一些特别具体的东西 —— 有可能是 text 类型的、数值类型的、数组类型的,或者其他什么类型!我不知道如何命名参数。所以 thing 看起来是最合适的参数名字了。
实现过程如下:
func inject(thing: T) {
textDependency = thing
}
我实在不喜欢 thing —— 不具有稳定性。所以今天早上,我想到了一个疯狂的解决方案,不用 thing 了,结果这方法竟然走得通!
protocol Injectable {
associatedType T
// 用 _ 替换掉 thing
func inject(_: T)
}
替换掉 thing,我在协议里把参数名字改成 _!
很明显,现在实现此协议时,我可以把参数命名成任何名字了。
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 翻译组翻译,已经获得作者翻译授权。