Linking Pages in Swift Playgrounds [Xcode]

How to link pages in swift playgrounds?

You can't connect playground pages, but you can share your source file, using the Sources folder in the projects Sources folder.

If your playground project is named User, you can put the source file in the User Sources folder, and it is available to all the sub-pages in the playground.

Remember to make your class, variables and functions public. If you don't specify it, it will only be visible within the Page.

In this example I have made a project named User and created a page User Object. I placed the User.swift file into the User Object Sources directory. It is available to the User Object page.

Playground example

I uploaded the example to my Github account - https://github.com/timtwotoes/UserPlayground

How can I pass data from a Playground Page to another Playground Page in Swift Playgrounds?

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:

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

Then, on the other page, you can retrieve the value with:

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.

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

And use this value for your key, like

let myKey = StoredVariableKeys.myVariable1.rawValue;

How to make a multipage Swift Playground

Yes, the markup formatting of Swift Playgrounds does support that. The syntax for it is

//: [Next Topic](@next)

Then you need to enable rendered markup for your playground, which you can do using Editor > Show Rendered Markup.

This is an Xcode and Swift playgrounds feature, it has nothing to do with SwiftUI or Swift itself.

For more information, see the Markup Formatting Reference Apple documentation.



Related Topics



Leave a reply



Submit