[英]Swift Default Parameter value with Delegate Reference
I am trying to do dependency injection in my code without using any framework, while refactoring I tried to pass dependency from outside. 我试图在不使用任何框架的情况下在代码中进行依赖项注入,而重构则尝试从外部传递依赖项。 Now issue which I am facing is declaration of delegate which is needed for default parameter value.
我现在面临的问题是默认参数值所需的委托声明。
init(service : MYService = MYService(withDelegate: self)) {
}
In above snippet, above object creation needs delegate from outside to transfer results. 在上面的代码片段中,上面的对象创建需要从外部进行委托才能传输结果。 In Swift is their any way to declare that self reference in parameter.
在Swift中,他们可以通过任何方式在参数中声明该自引用。
Technically it seems like at this point self is not created as this is init method, now I have another option which I would like to go with if there is no another way for achieving it. 从技术上讲,这时似乎没有创建self,因为这是init方法,如果没有其他实现方法,我现在想使用另一个选项。
That is creating MYService
object without delegate and I have to expose another method for accepting delegate. 那就是在没有委托的情况下创建
MYService
对象,我必须公开另一种接受委托的方法。
It seems a good approach to inject any service as i hope the MYService
class
also conform to some protocol
so that any service can be injected that conform to that protocol
. 注入任何服务似乎是一种好方法,因为我希望
MYService
class
也符合某种protocol
以便可以注入符合该protocol
任何服务。 Specific to this question i would like to recommend keep the delegate also as an injectable object as below, 对于这个问题,我想建议如下将代理也保留为可注入对象,
init(service: MYService = MYService(), serviceDelegate: MyServiceDelegate? = nil) {
if let delegate = serviceDelegate {
service.delegate = delegate
} else {
service.delegate = self
}
}
For this, you have to expose service delegate
which should be totally fine as this is how we have in Swift
( UITableView
, UITextField
etc) 为此,您必须公开服务
delegate
,这应该是完全可以的,因为这是我们在Swift
做法( UITableView
, UITextField
等)
As i think you want to make the class
that owns service
as default delegate
so i made the delegate
as optional
so that if its not there, this class will be the delegate otherwise if it will be the delegate
passed along initialization
. 我认为您想将拥有
service
的class
作为默认delegate
因此我将delegate
为optional
这样,如果不存在该委托,则该类将成为委托,否则,将其作为initialization
传递的delegate
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.