繁体   English   中英

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

[英]Swift Using an app level global constant in a library package

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

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

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)

我收到类似的错误消息。

我错过了什么?

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

struct Constants {
    static let apiKey = "YOUR_KEY_HERE"
}

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

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

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

可能是您的全局常量在应用程序层次结构中的错误位置声明。 使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
    ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM