Ios 台风-如何注入符合协议而不是类的参数
我有一个代表登录用户的类Ios 台风-如何注入符合协议而不是类的参数,ios,swift,dependency-injection,typhoon,Ios,Swift,Dependency Injection,Typhoon,我有一个代表登录用户的类 public class User: NSObject { init(authenticator: Authenticator) { self.authenticator = authenticator } ... } 它唯一的初始参数是符合身份验证协议的对象 protocol Authenticator { func authenticate(login:String , passwo
public class User: NSObject {
init(authenticator: Authenticator) {
self.authenticator = authenticator
}
...
}
它唯一的初始参数是符合身份验证协议的对象
protocol Authenticator
{
func authenticate(login:String , password:String , handler: (result:AuthenticationResult)->() )
}
在我的例子中,Auth对象是类后端服务的实例
我的组件定义是:
public dynamic func user() -> AnyObject {
return TyphoonDefinition.withClass(User.self) {
(definition) in
definition.useInitializer("initWithAuthenticator") {
(initializer) in
initializer.injectParameterWith( self.backendService() )
}
}
}
应用程序原因运行时错误
'Method 'initWithAuthenticator' has 0 parameters, but 1 was injected. Do you mean 'initWithAuthenticator:'?'
如果我将init方法更改为“initWithAuthenticator:”它将崩溃
'Method 'initWithAuthenticator:' not found on 'PersonalMessages.User'. Did you include the required ':' characters to signify arguments?'
目前,有必要将“@objc”指令添加到Swift协议中,使其可用于Typhone的依赖项注入。如果没有它,objective-c运行时的内省和动态调度功能将不可用,并且这些都是必需的
同样,在类的情况下,它必须从NSObjor扩展,或者具有'Objc '指令,否则它也将使用C++风格的VTISE调度,并且基本上没有反射。对于私有变量或方法,它们还必须具有“dynamic”修饰符
虽然vtable分派速度更快,但它阻止了Cocoa的许多最强大的功能(如KVO)所依赖的运行时方法拦截。因此,这两种范式都很重要,斯威夫特能够在它们之间进行切换,这令人印象深刻。但在协议的情况下,使用“@objc”指令有点不幸,因为它意味着“遗留”行为。也许“动态”会更好dynamic protocol Authenticator //Not supported but would've been a nicer than '@objc'?
或者,暗示需要动态行为的另一种方式是让协议扩展NSObject协议,但这不起作用。因此,使用“@objc”是唯一的选择
同时,对于类来说,扩展NSObject的要求在使用Cocoa/Touch应用程序时并不明显 如果init方法更改为
init(authenticator:BackendService)
它可以正常工作,问题是因为swift协议没有@obj
关键字