Home > Blockchain >  Swift Using an app level global constant in a library package
Swift Using an app level global constant in a library package

Time:12-25

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?

CodePudding user response:

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

CodePudding user response:

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.

  • Related