2

I have an ObservableObject class used to fetch data from an api. It takes one parameter which is the api key. I am trying to pass that key from a parameter of my ContentView to the object.

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

This works fine when I'm asking for a parameter in my struct

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

    var body: some View {
        //View
    }
}

However this doesn't:

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

I think i'm initialising the struct wrong as I am getting the error "Cannot find 'self' in scope"

Arnav Motwani
  • 707
  • 7
  • 26

1 Answers1

1

Initialize it inside init

struct ContentView: View {
    var clientId: String
    @ObservedObject var api: UnsplashAPI
    
    init(clientId: String){
        self.clientId = clientId
        self.api = UnsplashAPI(clientId: clientId)    // << here !!
    }
// ...
Asperi
  • 228,894
  • 20
  • 464
  • 690