簡體   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