我正在努力想出一种方法来减少使用Cleanse向ViewController
进行依赖注入的样板代码。但是,绝对卡在Cleanse.Component
样板的类型擦除类中。我做错了什么?
(包括Code和XCode快照,方便您阅读)
import Foundation
import Cleanse
protocol CleanseInjectable {
func inject(args: Any...) -> Void
func prepare() -> Void
}
extension CleanseInjectable {
func inject(args: Any...) -> Void {
}
}
class AnyCleansePropertyInjectionComponent<TargetType: AnyObject, CleanseInjectable>: Cleanse.Component {
typealias Root = PropertyInjector<TargetType>
func configure<B : Binder>(binder binder: B) {
binder
.bindPropertyInjectionOf(TargetType.self)
.to(injector: (TargetType.self as! CleanseInjectable.Type).inject)
}
}
我得到的错误与任何Swift协议错误一样奇怪,事后才明白这一点:Type 'CleanseInjectable' has no member 'inject'
?!
答案 0 :(得分:0)
此版本似乎可以解决错误!似乎Swift无法理解TargetType: AnyObject, CleanseInjectable
是否与protocol CleanseInjectable: class
相当于约束。
import Cleanse
protocol CleanseInjectable: class {
func inject(args: Any...) -> Void
func prepare() -> Void
}
extension CleanseInjectable {
func inject(args: Any...) -> Void {
}
}
class AnyCleansePropertyInjectionComponent<TargetType: CleanseInjectable>: Cleanse.Component {
typealias Root = PropertyInjector<TargetType>
func configure<B : Binder>(binder binder: B) {
binder
.bindPropertyInjectionOf(TargetType.self)
.to(injector: TargetType.inject)
}
}
编辑:我已完成的清洁锅炉板清除器(在运行时未经测试,最早将更新),以获得乐趣和灵感!
import Cleanse
protocol CleanseInjectable: class {
var cleanseComponent: AnyCleansePropertyInjectionComponent<Self>? { get }
func inject(args: Any...) -> Void
func prepare() -> Void
}
extension CleanseInjectable {
func inject(args: Any...) -> Void {
// Override me to do something useful, brah!
}
func prepare() -> Void {
if (cleanseComponent != nil) {
(try! cleanseComponent!.build()).injectProperties(into: self)
}
}
}
class AnyCleansePropertyInjectionComponent<TargetType: CleanseInjectable>: Cleanse.Component {
typealias Root = PropertyInjector<TargetType>
func configure<B : Binder>(binder binder: B) {
binder
.bindPropertyInjectionOf(TargetType.self)
.to(injector: TargetType.inject)
}
}