I am making an PlaygroundBook for Swift Playgrounds [Not Xcode Playgrounds]. I want pass data between playground pages.
Example, I have an public variable in UserModule and its value is 0. In first page, user change this variable to 1. When user go to second page, variable's value is 0. But I want its value is user's value (1). How can I do that?
I'm using SwiftUI. I tried to use UserDefaults but UserDefaults won't work truly in Swift Playgrounds. And also try to save datas to a JSON file but Playground won't write files (only read). I also tried this but it isn't work too.
Example, I have an public variable in UserModule and its value is 0. In first page, user change this variable to 1. When user go to second page, variable's value is 0. But I want its value is user's value (1). How can I do that?
I'm using SwiftUI. I tried to use UserDefaults but UserDefaults won't work truly in Swift Playgrounds. And also try to save datas to a JSON file but Playground won't write files (only read). I also tried this but it isn't work too.
Answered on another forum.
You'll want to use PlaygroundKeyValueStore. This works similar to UserDefaults, but on playgrounds. Keep in mind that it only deals with PlaygroundValues, so you'll have to wrap your value.
You can do something like:
Then, on the other page, you can retrieve the value with:
You should probably also store you keys on an enum, for example, to avoid mistyping.
And use this value for your key, like
You'll want to use PlaygroundKeyValueStore. This works similar to UserDefaults, but on playgrounds. Keep in mind that it only deals with PlaygroundValues, so you'll have to wrap your value.
You can do something like:
Code Block public var myVariable = 0 { didSet { PlaygroundKeyValueStore.current.keyValueStore["myKey"] = .integer(myVariable) } }
Then, on the other page, you can retrieve the value with:
Code Block guard let keyValue = PlaygroundKeyValueStore.current.keyValueStore["myKey"], case .integer(let storedValue) = keyValue else { // Deal with absence of value } // Use retrieved value
You should probably also store you keys on an enum, for example, to avoid mistyping.
Code Block enum StoredVariableKeys: String { case myVariable1 /* ... */ }
And use this value for your key, like
Code Block let myKey = StoredVariableKeys.myVariable1.rawValue;