我想为我的班级创建 init ,它可能看起来像这样:
initWithSomeMode { // Not compilable
self.init()
self.customSetup()
}
Run Code Online (Sandbox Code Playgroud)
当然上面的代码不起作用,我只是想展示我想要实现的目标。
我只能在 Swift 类中看到方便的 init,但在这种情况下,我需要添加参数,但我不需要它们。
所以,我可能会通过方便的 init 来实现这一点:
convenience init(foo: String?) {
self.init()
self.customSetup()
}
Run Code Online (Sandbox Code Playgroud)
有没有办法创建没有参数的自定义初始化?
您需要创建一个static方法:
static func initWithSomeMode() -> YourClass {
let obj = YourClass()
obj.someCustomSetup()
return obj
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
let yourClass = YourClass.initWithSomeMode()
Run Code Online (Sandbox Code Playgroud)