Random Picker in Swift Playgrounds

by ambersidereal in Circuits > Apple

10 Views, 0 Favorites, 0 Comments

Random Picker in Swift Playgrounds

IMG_3632.png

Swift Playgrounds is a coding app for students that uses Apple’s programming language. However, it is hard to find knowledge on Swift Playgrounds online. I made this project because I spend a lot of time looking up how to make a random picker in the app. This instructable outlines how to do it.

Supplies

If you don’t already have it, the app can be downloaded on the App Store.

It is available on iPad and Mac.

The Code

IMG_3632.png

The code includes a list with the objects to pick from. I named it “projects” because this was a duplicate of an old project that randomly generates maker project ideas from a selection.

Ignore “var shown”, it doesn’t really matter, I just forgot to delete it.

The code that determines the random choosing is “let randomName = projects.randomElement()!” This code allows a random element from the list to be chosen. Then text is generated with randomName’s value on it.

The button, when pressed, toggles isOn, which allows the if boolean to be true.

If you’re not understanding all of this, just copy the code and put it in Playgrounds. You’ll get a random picker.