In the first recipe, we will get up and running with Swift using a Swift Playground, and we will run our first piece of Swift code.
Your first Swift program
Getting ready
To run our first Swift program, we need to download and install our IDE. During the beta of Apple's Xcode 9, it is available as a direct download from Apple's developer website at http://developer.apple.com/download, access to this beta will require a free Apple developer account. Once the beta has ended and Xcode 9 is publicly available, it will also be available from the Mac App Store. By obtaining it from the Mac App Store, you will be informed of updates automatically, so this is the preferred route once Xcode 9 is out of beta.
Downloading Xcode
Follow these steps to download Xcode from the Mac App Store:
- Open up the Mac App Store, either from the dock or via Spotlight:
- Search for xcode:
- Click on Install:
- The progress can be monitored from Launchpad:
Follow these steps to get Xcode as a direct download:
- Go to the Apple Developer download page at http://developer.apple.com/download:
- Click on the Download button to download Xcode within a .xip file:
- Double-click on the downloaded file to unpack the Xcode application.
- Drag the Xcode application into your Applications folder:
How to do it...
With Xcode downloaded, let's create our first Swift playground:
- Launch Xcode from the icon in your dock.
- From the welcome screen, choose Get started with a playground:
- From the template chooser, select the blank template from the iOS tab:
- Choose a name for your playground and a location to save it:
- You are now presented with a view that looks like this:
- Let's replace the word playground with Swift!.
- Click on the blue play icon in the bottom left-hand corner of the window to execute the code in the playground:
- Congratulations! You have just run some Swift code.
- On the right-hand side of the window, you will see the output of each line of code in the playground. We can see that our line of code has output "Hello, Swift!":
There's more...
If you put your cursor over the output on the right-hand side, you will see two buttons: one that looks like an eye and another that is a rounded square:
Click on the eye button to get a Quick Look box of the output. This isn't that useful for just a string, but can be useful for more visual output, such as colors and views:
Click on the square button, and a box will be added in-line, under your code, showing the output of the code. This can be really useful if you want to see how the output changes as you change the code:
See also
We will learn more about playgrounds and how we can take them further in Chapter 6, Swift Playgrounds.