Alexandr Gromov
Alexandr Gromov

Reputation: 5

closure through typealias swift not working

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

Upvotes: 0

Views: 63

Answers (2)

hell0friend
hell0friend

Reputation: 569

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

Upvotes: 0

Rob
Rob

Reputation: 437882

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.

Upvotes: 2

Related Questions