我正在创建一个单例以用作我的应用程序中的模型。初始化过程包括一个 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 中提取。