[英]closure through typealias swift not working
why does typealias closure not transmit data and output nothing to the console?为什么 typealias 闭包不向控制台传输数据和 output 什么都没有? How to fix it?如何解决?
class viewModel: NSObject {
var abc = ["123", "456", "789"]
typealias type = ([String]) -> Void
var send: type?
func createCharts(_ dataPoints: [String]) {
var dataEntry: [String] = []
for item in dataPoints {
dataEntry.append(item)
}
send?(dataEntry)
}
override init() {
super.init()
self.createCharts(abc)
}
}
class ViewController: UIViewController {
var viewModel: viewModel = viewModel()
func type() {
viewModel.send = { item in
print(item)
}
}
override func viewDidLoad() {
super.viewDidLoad()
print("hello")
type()
}
}
I have a project in which a similar design works, but I can not repeat it我有一个类似设计的项目,但我不能重复
The pattern is fine, but the timing is off.模式很好,但时机不对。
You're calling createCharts
during the init
of the view model.您在视图 model 的init
期间调用createCharts
。 But the view controller is setting the send
closure after the init
of the view model is done.但是视图 controller 在视图 model 的init
完成后设置send
关闭。
Bottom line, you probably don't want to call createCharts
during the init
of the view model.底线,您可能不想在视图 model 的init
期间调用createCharts
。
Possible solution is to create custom initializer:可能的解决方案是创建自定义初始化程序:
class viewModel: NSObject {
...
init(send: type?) {
self.send = send
self.createCharts(abc)
}
}
class ViewController: UIViewController {
var viewModel: viewModel = viewModel(send: { print($0) })
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.