Swift在库包中使用应用程序级全局常量



这应该很容易,但它让我陷入了困境。

在我的应用程序中,我有一个定义为的全局常量

public let apiKey = "hjbcsddsbsdjhksdbvbsdbvsdbvs"

我想在我作为SwiftPackage添加到项目中的库中使用apiKey。我需要在图书馆里用它来启动一项服务。

Library.configure(withAPIKey: apiKey)

但是我得到错误

Cannot find apiKey in scope

我尝试过将apiKey包装成这样的结构:

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

并以此方式使用:

Library.configure(withAPIKey: globalConstants.apiKey)

我收到了类似的错误消息。

我错过了什么?

可能是您的全局常量在应用程序层次结构中的错误位置声明的。使得CCD_ 1不是"1";参见";CCD_ 2。

虽然这是一个SwiftUI的例子,但它是有效的,你可以做一些事情在您的特定应用程序中类似。

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

您可以通过拥有一个Constants.swift文件来完成类似的操作:

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

然后,假设您从调用常量的文件与该Constants.swift文件位于同一项目和目标中,您可以如下调用它:

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

如果这不起作用,请检查这个新文件是否真的包含在项目中以及是否是目标的成员。这可能就是你的问题所在。

附带说明一下,在将API密钥、机密和其他敏感信息添加到应用程序的代码库时要小心。例如,您可能希望将其添加到.gitignore文件中。

最新更新