SwiftUI:使用ObservableObject模型视图中的函数初始化数据时出错

问题描述 投票:0回答:1

我在获取数据并返回在模型视图中声明的变量时遇到问题:

struct ExploreDataSource: Decodable {
    var places: [Place]
}

class ExploreViewModel: ObservableObject {

    var dataSource: ExploreDataSource

    init () {
        dataSource = fetchDataSource()
    }

    func fetchDataSource () -> ExploreDataSource {
        var dataSourceRes = ExploreDataSource(places: [])
        let request = URLRequest(url: URL(string: APIEndPoint.getExploreURL())!)
        URLSession.shared.dataTask(with: request, completionHandler: { data, response, err in
            guard let data = data else { return }
            do {
                let decoder = JSONDecoder()
                let resData = try decoder.decode(ExploreDataSource.self, from: data)
                DispatchQueue.main.async {
                    dataSourceRes = resData
                }

            } catch {
            }
        }).resume()
        return dataSourceRes
    }

}

错误:

'self' used in method call 'fetchDataSource' before all stored properties are initialized

init功能行中。

swift swiftui
1个回答
0
投票

您执行此操作:

init () {
    dataSource = fetchDataSource()
}

填充您的dataSource->并在获取中...您在填充dataSource之前使用(!)。这是不允许的。您可以将dataSource声明为Optional或在init中将其填充为空。

在一个类中,必须先填充该类本身的所有变量,然后才能使用“ self”。

© www.soinside.com 2019 - 2024. All rights reserved.