closure through typealias swift not working

∥☆過路亽.° 提交于 2020-04-17 17:59:24

问题


why does typealias closure not transmit data and output nothing to the console? 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


回答1:


The pattern is fine, but the timing is off.

You’re calling createCharts during the init of the view model. But the view controller is setting the send closure after the init of the view model is done.

Bottom line, you probably don’t want to call createCharts during the init of the view model.




回答2:


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) })
    ...
}


来源:https://stackoverflow.com/questions/61163732/closure-through-typealias-swift-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!