【问题标题】:How can I pass data from a Playground Page to another Playground Page in Swift Playgrounds?如何将数据从 Playground 页面传递到 Swift Playgrounds 中的另一个 Playground 页面?
【发布时间】:2021-04-13 10:45:41
【问题描述】:

我正在为 Swift Playgrounds [不是 Xcode Playgrounds] 制作 PlaygroundBook。我想在游乐场页面之间传递数据。例如,我在 UserModule 中有一个公共变量,它的值为 0。在第一页,用户将此变量更改为 1。当用户转到第二页时,变量的值为 0。但我希望它的值为用户的值 (1)。我该怎么做?

我正在使用 SwiftUI。我尝试使用 UserDefaults,但 UserDefaults 在 Swift Playgrounds 中无法真正发挥作用。并且还尝试将数据保存到 JSON 文件,但 Playground 不会写入文件(仅读取)。我也试过this,但它也不起作用。

【问题讨论】:

    标签: swift swift-playground


    【解决方案1】:

    您需要使用PlaygroundKeyValueStore。这类似于UserDefaults,但在操场上。请记住,它只处理PlaygroundValues,因此您必须包装您的值。

    你可以这样做:

    public var myVariable = 0 {
        didSet {
            PlaygroundKeyValueStore.current.keyValueStore["myKey"] = .integer(myVariable)
        }
    }
    

    然后,在另一个页面上,您可以通过以下方式检索该值:

    guard let keyValue = PlaygroundKeyValueStore.current.keyValueStore["myKey"],
        case .integer(let storedValue) = keyValue else {
        // Deal with absence of value
    }
    // Use retrieved value
    

    您可能还应该将密钥存储在枚举中,例如,以避免输入错误。

    enum StoredVariableKeys: String {
        case myVariable1
        /* ... */
    }
    

    并将此值用作您的密钥,例如

    let myKey = StoredVariableKeys.myVariable1.rawValue;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 2017-01-25
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多