0

这应该很容易,但它让我卡住了。

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

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)

我收到类似的错误消息。

我错过了什么?

4

2 回答 2

0

可能是您的全局常量在应用程序层次结构中的错误位置声明。使Library.configure(withAPIKey: apiKey)不“看到”的apiKey

尽管这是一个有效的 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
    ...
}
于 2021-12-24T08:34:28.803 回答
-1

Constants.swift你可以通过有一个文件来做这样的事情:

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

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

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

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

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

于 2021-12-23T18:48:58.127 回答