Use SwiftUI in a Playground

Let your imagination run wild!

Image for post
Image for post
Photo by Mink Mingle on Unsplash

Playgrounds are a fantastic way of producing code, and you don’t even need a device in order to do so.

But how can you combine your love of SwiftUI with your love of Playgrounds? Read on.

Difficulty: Beginner | Easy | Normal | Challenging


Recommended: Be able to produce a “Hello, World!” Swift application (guide HERE)


Playgrounds: A development environment that can be used to create Swift code

Swift: An open source programming language for macOS, iOS, watchOS and tvOS

Creating a Playground: On a Mac

You do need to have downloaded and installed Xcode on your machine

You can then go through the menu File > New Playground

I then choose iOS > New Playground in the following screen. By choosing iOS we get UIKit imported for us (which is great, as we need that)

Image for post
Image for post

You’ll need to choose a destination for your Playground as you go. Here is a visual guide:

Image for post
Image for post

You’ll have seen from that video, when I run var str = "Hello, playground") print("Hello, playground") console/debug panel appears at the bottom of the screen. Which brings us to a good opportunity to highlight the main areas of the screen:

Image for post
Image for post

The SwiftUI section

The key here is to use UIHostingController to, well, host your content view.

You’d like a code example? No problem:

Image for post
Image for post
Click for Gist

This displays the traditional Hello, world! String right in the middle of the screen on the right of the Playground — SwiftUI style!

If you can’t see the result (which should look like the following):

Image for post
Image for post

You can use the live view shortcut by typing option-command-enter on your keyboard that toggles the live view on and off. Woudn’t that be great?


Yeah playgrounds! Yeah SwiftUI.

Together? Finally.

This is the article that has (hopefully) helped you to do just that.

If you’ve any questions, comments or suggestions please hit me up on Twitter

Feel free to sign up to my newsletter

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store