使用完成处理程序创建Swift Singleton

时间:2015-09-23 11:25:33

标签: ios swift callback singleton completionhandler

我正在创建一个单例,用作我的应用中的模型。初始化过程包括API调用,因此我需要使用完成处理程序。问题是私有初始化程序包含使用公共属性实例化的完成处理程序。如何在get实例调用中添加完成处理程序以确保数据已加载?

到目前为止,这是代码,API调用错过了清晰度。

import Foundation

struct Country {
    var name: String
    var region: String
    var subRegion: String
}

class Countries {

    var countryData = [Country]()

    // how do I call it?
    static let getInstance = Countries()

    private init(completionHandler: (Bool)) {
        // do some async stuff
        completionHandler(true)
    }

}

// this is how I envisage calling it from my controller.

Countries.getInstance(completionHandler: {() -> Void in
    // the data is available now so we can do stuff with it, such as making calls to extract specific data.
})

我可能过度复杂化了这个过程,但是在尝试使用单例之前,需要绝对确信数据已从API中提取出来。

0 个答案:

没有答案