Swift Playgrounds with UIKit in Xcode 6

In Xcode 5 and prior I often found myself with folders full of iOS projects with names such as Test, Testing, TestCollection and so on. Xcode 6 adds a new project type known as Swift Playground that should help alleviate this issue. Plus there is no better place to start learning Swift. If you have an Apple Developer account, feel free to follow along after you install the Xcode 6 beta.

Let’s get started. In the Welcome to Xcode window, click the Get started with a playground button.

You will then be prompted to choose a location to save the new playground. Do so and an empty playground will open.

Wait, what is this import Cocoa nonsense?! We want to play with UIKit so let’s change the playground type to iOS. Open the File Inspector with View ➤ Utilities ➤ Show File Inspector (⌥⌘1). After that, change thePlatform setting to iOS.

Last, change import Cocoa to import UIKit on line 3.

We are now set up to start playing with UIKit. Let’s make a quick UILabel to test it out and to practice previewing the label in the Assistant Editor. Enter the following code into the Playground.

Open the Assistant Editor withView ➤ Assistant Editor ➤ Show Assistant Editor (⌥⌘⏎). Afterwards, click the Value History button on the line after item number 2. This will add the label to the Assistant Editor and will automatically update whenever it’s properties are changed.

To test that this is working, let’s change a few more things on the label.

This code is fairly straightforward and shouldn’t look too much different from Objective-C. It simply changes the background color, aligns the text to the center of the label and rounds the corners. Better yet, after you change the last line, the label preview in the Assistant Editor will update immediately with the changes.

To top this all off, the value history setting allows you to see different stages along the history by tracking the variable at different points. Let’s change the code to the following to see how the label looks with a blue background and rounded corners.

So there you have it, a custom UILabel ready to copy into and use in your next iOS project. While this is a smaller example, you should no doubt quickly see the worth of this new feature and will have a playground in every app that you work on. Maybe we can all delete those test project folders that have been stacking up as well.

Feel free to leave a comment if you have any thoughts or would like to see any other tutorials.