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?
You could do something like this by having a Constants.swift
file:
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.
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
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.