将参数值传递给 Observable 对象

Passing parameter value to Observable object

我有一个 ObservableObject class 用于从 api 获取数据。它需要一个参数,即 api 键。我正在尝试将该键从我的 ContentView 的参数传递给对象。

class UnsplashAPI: ObservableObject {
    //some code
    var clientId: String
    
    init(clientId: String) {
        self.clientId = clientId
    }
    //some more code
}

当我在我的结构中请求参数时这很好用

struct ContentView: View {
    
    @ObservedObject var api = UnsplashAPI(clientId: "APIKEY")

    var body: some View {
        //View
    }
}

然而这不是:

struct ContentView: View {
    var clientId: String
    @ObservedObject var api = UnsplashAPI(clientId: self.clientId) // Cannot find 'self' in scope
    
    init(clientId: String){
        self.clientId = clientId
    }
    
    var body: some View {
        //View
    }
}

我认为我正在初始化结构错误,因为我收到错误“在范围内找不到 'self'”

在里面初始化init

struct ContentView: View {
    var clientId: String
    @ObservedObject var api: UnsplashAPI
    
    init(clientId: String){
        self.clientId = clientId
        self.api = UnsplashAPI(clientId: clientId)    // << here !!
    }
// ...