0

This should be easy but its got me stuck.

In my app, I have a global constant defined as

public let apiKey = "hjbcsddsbsdjhksdbvbsdbvsdbvs"

I want to use that apiKey in a library that I have added to my project as a SwiftPackage. I need it in the library to initiate a service.

Library.configure(withAPIKey: apiKey)

but I get the error

Cannot find apiKey in scope

I have tried wrapping the apiKey into a struct like so:

public struct globalConstants {
    static let apiKey = "hjbcsddsbsdjhksdbvbsdbvsdbvs"
}

and using it as such:

Library.configure(withAPIKey: globalConstants.apiKey)

and I get a similar error message.

What am I missing?

Ferdinand Rios
  • 972
  • 6
  • 18

2 Answers2

0

It could be that your global constant is declared in the wrong place in the hierarchy of your app. Making the Library.configure(withAPIKey: apiKey) not "see" the apiKey.

Although this is a SwiftUI example, that works, you can do something similar in your particular app.

import SwiftUI
import OWOneCall   // <-- my SwiftPackage library 


// -- here the app "global" constant declaration
public let apiKey = "hjbcsddsbsdjhksdbvbsdbvsdbvs"

// here the app 
@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

// elsewhere in my app
struct ContentView: View {
    // OWProvider is in my SwiftPackage library
    let weatherProvider = OWProvider(apiKey: apiKey) // <-- here pass the apiKey to the library
    ...
}
-1

You could do something like this by having a Constants.swift file:

public struct Constants {
    static let apiKey = "YOUR_KEY_HERE"
}

Then, assuming the file you're calling the constant from is in the same project and target as this Constants.swift file, you can call it as follows:

print(Constants.apiKey) // prints "YOUR_KEY_HERE"

If this doesn't work, check if this new file is actually included in the project and a member of your target. That might be the issue in your case.

As a side note, be careful when adding API keys, secrets, and other sensitive information to your application's codebase. You might want to add it to your .gitignore file, for example.

Bjorn B.
  • 506
  • 3
  • 10
  • Thank you, but unfortunately what I am trying to achieve is actually using the value in a library which is NOT in the same project. – Ferdinand Rios Dec 23 '21 at 22:01
  • I mean that the `Constants.swift` and the file you're calling the library from should be in the same project and target (otherwise the file cannot find the constants file). You should pass the `Constants.apiKey` as an argument to the library's method. What's the library you're using and the method you are trying to call? – Bjorn B. Dec 24 '21 at 09:56