{infiniteZest}
// Articles. Tutorials. Utilities.
Home  |   Search  |   Login  
Categories Skip Navigation Links
New / All
AJAX
Apple
ASP.NET
.NET
Git
Google / Android
Python / IronPython
Miscellaneous
SQL Server
Swift - Playgrounds and REPL
Summary
This article introduces the Playgrounds - a powerful tool to learn and play with Swift code. It also talks about REPL command line interpreter and IBM’s Swift Sandbox.
 
Table of Contents

Playgrounds

Creating a New Playground

Figure 1. Create a playground for iOS or OS X or tvOS

Understanding Playground Window

Figure 2. Playground window annotated

REPL

IBM Swift Sandbox

Figure 3. IBM Swift Sandbox

 
Article Series
Previous Article: This is the First Article of the Series
This article is part of the Series:
Swift - Introduction and Basics
Next Article:
Test Your Knowledge: Swift - Playgrounds and REPL

Playgrounds

Playgrounds are a great way to develop, test, and play with pieces of Swift code without having to create brand new projects. You can type out (or copy-paste) Swift code in a sophisticated console like environment that is interactive. Results are immediately available without having to compile the source. This code can be saved to continue at a later date.

The Playgrounds stand out for two tasks:

  • A learning environment: type / play with only the things that you are currently learning, instead of putting a lot of surrounding code to make something work
  • A prototyping environment: quickly develop / perfect an area in your app / project and then copy-paste or include the code back into the real project

Creating a New Playground

A new Playground can be created from the Xcode welcome window by clicking on ‘Get started with a playground’. Or it can be created from the Xcode menu - using File - New - Playground… . One playground works in only one environment:

  • OS X
  • iOS
  • tvOS

So, if you are testing your code in iOS playground and then if you want to see how it works on OS X, you would then have to create a separate playground for OS X and test it there. Of course, the code needs to modified according to what works in that specific environment.

For example, in the iOS playground, you might import UIKit with the following line:

import UIKit

That line won’t work in the OS X playground. It will complain that there is no such module ‘UIKit’ — which is true, OS X doesn’t have UIKit. You might have to do something like:

import Cocoa
// This imports Foundation, AppKit, and CoreData

Figure 1. Create a playground for iOS or OS X or tvOS

Figure 1. Create a playground for iOS or OS X or tvOS

All the Swift code that you type into the above playground will be saved into an OS X package called MyiOSPlayground.playground. A package in OS X is a file system directory. If you right-click on the above playground file in the OS X Finder, you will see a menu item called ‘Show Package Contents …’ If you click on that, you will see the files in this package. The file Contents.swift contains the Swift code that you type into the playground.

Understanding Playground Window

The Playground window provides powerful UI that contains the 3-column format that you are familiar with in Xcode.

Figure 2. Playground window annotated

Figure 2. Playground window annotated

As you can see in the figure above, Playground provides a convenient way to execute Swift code without bothering to setup an entire project:

In the center there is an Editor, which can show images and colors and other literals along side the code.

Statements are continually evaluated in the right column as they are typed. You cannot put breakpoints, but this gives lot of information about what’s going on in the program.

The entire playground doesn’t have to have just one file (though most of the playgrounds might be done just one - which would be named Contents.swift). You can add files from the left pane - both source files and Resources like png files which are then referred to in the code.

If you want to know more of the state of the program, you can use the print() function. The results from the print() function are printed in the bottom window.

You can see a familiar toolbar at the top (familiar to Xcode developers) that provides additional functionality like source versioning, quick help / access to Apple help documentation, etc.

REPL

REPL stands for Read-Eval-Print-Loop. This is command line program where Swift statements/programs can be executed. This is similar to the interpreter you find in some other languages like Python and Ruby.

You can start this REPL interpreter from the Terminal by issuing any of the following three commands:

  • swift
  • xcrun swift
  • lldb —repl

In all those cases, an interactive interpreter will open up, where you can type Swift code to execute.

swift
Welcome to Apple Swift version 2.2 (swiftlang-703.0.18.8 clang-703.0.30). Type :help for assistance.
  1>

// If it’s one of the Swift 3.0 builds, it will look like this
Welcome to Apple Swift version 3.0-dev (LLVM cb08d1dbbd, Clang 383859a9c4, Swift 9e8266aaeb). Type :help for assistance.
  1>

REPL is interactive. It comes with the evaluator (of Swift code) and lldb (the debugger is integrated into this command line interpreter). You can’t use UIKit (however AppKit is supported on OS X) here though - Playgrounds is better solution for doing anything graphical.

To keep the flow of code going, you can re-declare variables again and again. REPL will simply take the last declaration. In the code below n is first declared as String then re-declared as Int. In Playgrounds or regular code in Xcode this will be an error, but in the interpreter this is useful, because the editing capabilities are not super convenient or powerful (compared to Playgrounds and Xcode)

1> var n = "Thomas"
n: String = “Thomas"

  2> print(n)
Thomas

  3> var n = 20
n: Int = 20

  4> n+50
$R0: Int = 70

  5> $R0+20
$R1: Int = 90

As you can see results and print() function output are printed right away in the line below the typed command. Variables without names are identified as $R0, $R1, etc. You can also refer to these variables in the code.

Commands for REPL interpreter start with : - so, to quit, type :quit at the prompt. You can use arrow keys to move around in the ‘editor’ - by pressing the up arrow, you can see the previous statement, etc. Since debugger is included with this, full set of debugger commands are available - type :help to get the full listing of commands.

You can set a breakpoint by using :b <line number>

// Create a function - just type in the code, REPL provides formatting
1> func add(x: Int, _ y: Int) -> Int {
  2. return x+y
  3. }

// Set a breakpoint at line 2
  4> :b 2
Breakpoint 1: where = $__lldb_expr2`__lldb_expr_1.add (Swift.Int, Swift.Int) -> Swift.Int + 12 at repl.swift:2, address = 0x00000001004fd07c

// Call the function
  4> add(4, 5)

// Now breakpoint is hit and we are in lldb — the prompt changes.
Execution stopped at breakpoint. Enter LLDB commands to investigate (type help for assistance.)
Process 9020 stopped
* thread #1: tid = 0x146a3a, 0x00000001004fd07c $__lldb_expr2`add(x=4, y=5) -> Int + 12 at repl.swift:2, queue = ’com.apple.main-thread’, stop reason = breakpoint 1.1
    frame #0: 0x00000001004fd07c $__lldb_expr2`add(x=4, y=5) -> Int + 12 at repl.swift:2
   1 func add(x: Int, _ y: Int) -> Int {
-> 2 return x+y
   3 }
   4 add(4, 5)

// Step In
(lldb) s
Process 9020 stopped
* thread #1: tid = 0x146a3a, 0x00000001004fd146 $__lldb_expr4`main + 118 at repl.swift:4, queue = ’com.apple.main-thread’, stop reason = step in
    frame #0: 0x00000001004fd146 $__lldb_expr4`main + 118 at repl.swift:4
   1 func add(x: Int, _ y: Int) -> Int {
   2 return x+y
   3 }
-> 4 add(4, 5)

// Step In again a couple of times
(lldb) s

(lldb) s

// And now back to the interpreter prompt
  5>

As you can see above, setting breakpoints is relatively easy (this is a command line program, not a program with graphical UI). You can step through the code and get the program state by using other commands.

IBM Swift Sandbox

IBM has a web-based REPL - a Swift Sandbox - giving the ability to type Swift code on the left side of the window, and then execute and see the results on the right side of the window.

Execution of Swift is done on a Linux server (Swift at this point is officially supported on Apple platforms and Ubuntu Linux with more to come later)

Figure 3. IBM Swift Sandbox

Figure 3. IBM Swift Sandbox

You can play with this IBM Swift Sandbox from this location:

IBM Swift Sandbox

The editor on the left is pretty nice — includes line numbers and syntax coloring. A few interesting things to remember here:

Since the execution is a Linux box, remember that there is no UIKit or AppKit. So, if you try to import UIKit or import AppKit, it will tell you that there is no such module. So, if you would like to test any iOS or OS X code that uses UI code, then Playgrounds would be the option. If you want ‘server-like’ code (or code with no UI) that you want to run on Linux box, then IBM Swift Sandbox offers a convenient solution.

If you try to import UIKit from Apple’s REPL on OS X (the command line utility discussed above), you will get the same problems (at the time of this writing - may change later). If you develop on Mac (probably) and have no ready/easy access to a Linux box, IBM Swift Sandbox provides a great way to test your code quickly.

Take a Quick Quiz on this Article

1. If you want to write and test a code snippet that requires UIKit - without creating a project - which of the following is the best option?



: No project
Question 1 of 5
Article Series
Previous Article: This is the First Article of the Series
This article is part of the Series:
Swift - Introduction and Basics
Next Article:
Test Your Knowledge: Swift - Playgrounds and REPL
Bookmark and Share This

More Articles With Similar Tags
icon-swift-series.jpg
This series of articles goes through the basics of Swift. It introduces Playgrounds and REPL; Variables and Constants; Int, Float, Bool; Tuples, Type Aliases, Type Inference, Type Safety, and more.
icon-swift-test.jpg
Test on playgrounds and REPL in Swift.
icon-swift-article.jpg
Tags: bool, types, swift
This article discusses the boolean types in Swift and contrasts with how these types are used in C and Objective-C.
icon-swift-test.jpg
Tags: bool, types, swift
Test on Boolean Types in Swift.
icon-swift-test.jpg
Test on comments, structured comments, and markup in Swift
About  Contact  Privacy Policy  Site Map