Doodling With Swift 3: The Read-Eval-Print Loop

Written by: Reinder de Vries, September 15 2016, in Development

Everything apps isn’t all Swift, and everything Swift isn’t all Xcode. You can code in the Swift programming language without Xcode – with numerous benefits.

In this article you’ll dive in the “REPL”, which is a way to code Swift without using Xcode (and all its overhead). Getting used to doodling Swift in a REPL can greatly increase your understanding of the language, and of programming, when you’re learning how to code.

Ready? Let’s go.

Read-Eval-Print-What?

The REPL, or read-eval-print loop, is a simple interactive code editor in which you can type Swift code and let it execute immediately after. It does not have an extensive programming environment, like Xcode, nor does it have an iPhone Simulator. It’s pure Swift!

“REPL” looks like a weird name, but it is exactly what the editor does. First, it reads your code. It then evaluates that code, interpreting it line by line, and feeding it to a Swift compiler. Finally, the compiler executes the code and returns the output to your editor window.

Some REPLs literally read line-by-line, so you type one line, hit return, and the line is executed, returning the output back to you. Other editors allow you to type up an entire file of multi-line code, which is executed as a whole, and then returns the output to you, too.

If you’ve installed Xcode 8, you have access to a simple Swift REPL via the command-line. Start up Terminal, and type:

$ swift

(You don’t have to type the $, that’s just to indicate the example is a CLI command.)

The Swift REPL starts, and you see:

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

You can immediately start typing. When you hit return, your code executes. Why don’t you try it?

var meaning = 42

Swift reports your code back to you, but nothing meaningful really happens – you’ve only declared and initialized a variable. Let’s have it print the variable back to us!

print(meaning)

Output:

1> var meaning = 42
    meaning: Int = 42
2> print(meaning)
    42
3>  

NICE!

The Swift REPL has support for multi-line code, but it’s not very convenient. Try typing a opening squiggly bracket { and then hit return again. The REPL now indents your code for you, just like you would format your own code in Xcode.

Crafting Swifty Sandbox Castles…

Let’s switch to a nicer REPL, the IBM Swift Sandbox: https://swiftlang.ng.bluemix.net/#/repl.

It’s exactly what you think it is: a Swift editor in your browser window. Neat, right?

Remove the sample code, and start typing on line 1:

var meaning = 2 * 3 * 7
print(meaning)

If you then press the Command-S key the editor executes your code and shows the result in the right window.

42

Now that we have a simple editor at our disposal, let’s code a bit more. Copy the following code over to your own sandbox.

func pythagoras(a:Double, b:Double) -> Double
{
    return sqrt(pow(a, 2) + pow(b, 2))
}

As you can see, we’re using the Pythagoras Theorem to calculate the length of a side “c” of a right-angled triangle based on sides “a” and “b”.

When you execute your code, you should see an error:

ERROR at line 3, col 12: use of unresolved identifier 'sqrt'
return sqrt(pow(a, 2) + pow(b, 2))

WHOAH! What happens here? The Swift compiler complains it doesn’t know the function sqrt – that’s because we haven’t imported it yet. Just like in Xcode, you need to import functions, classes etc. from the standard Swift library and Cocoa Touch SDKs. For the sqrt and pow functions, this comes from the Foundation library.

Add this at the top of the editor to import it:

import Foundation

Note: the sqrt simply takes the square root of the first argument of the function, and the pow returs the first argument x raised to the power y. The Pythagorean Theorem says a² + b² = c², so the square root of a² + b² equals c.

Next up, let’s actually use our function. Do you know by heart what a 3-4-n right-angled triangle’s c-side is? It’s 5 – one of those math tricks that got drilled into you during highschool. With it, we can test if our function does what it’s supposed to do:

Add this below the function, in the editor:

let c = pythagoras(a: 3, b: 4)
print(c)

The entire code now looks like this:

import Foundation

func pythagoras(a:Double, b:Double) -> Double
{
    return sqrt(pow(a, 2) + pow(b, 2))
}

let c = pythagoras(a: 3, b: 4)
print(c)

Execute! What does it say?

5.0

NICE! Well done.

(Another such “Pythagorean triple” is 5-12-n. What’s n, here?)

Let’s Nerd Out Over Maths, Code And Solving Problems

All experts paint and sketch artists “doodle” in their free time. Why wouldn’t a Swift coder play with a little code, too?

Programming “headless” Swift, on such a blank canvas, can seem daunting at first, but the sandbox and the REPL can greatly increase your skill in coding and help you come up with free-form snippets of code. The editor is bare-bones too, so it might help you increase your immediate knowledge of Swift syntax and keywords.

Programming and math are close cousins, because many programming principles found their roots in mathematics. Likewise, programming empowers math by adding the powers of automatic computation.

Ever heard of Project Euler? Take a look!

Project Euler is a set of maths problems that can be solved with programming. It helps you learn to code, learn how to solve problems, and hopefully will teach you something about code efficiency.

Writing effective algorithms is something too broad to cover in this article, but I want to point out Project Euler to you anyway.

Take the first problem, for example:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

Can you code that in Swift? Good luck!

Join 11.000+ app developers and marketers
  • Get a weekly curated list of app development tools, articles and resources in your inbox
  • 10x your app installs with relevant App Store Optimization and app marketing strategies
  • BONUS: Grab a free copy of the App Toolbox 2017 to supercharge your next app project
Yes, Sign Me Up!

Most Popular Content

Written By: Reinder de Vries

Reinder de Vries is an indie app maker who teaches aspiring app developers and marketers how to build their own apps at LearnAppMaking.com. He has developed 50+ apps and his code is used by millions of users all over the globe. When he’s not coding, he enjoys strong espresso and traveling.

Got a killer app idea?

Grab the App Toolbox 2017 to learn how to save time building your app,
and how to 10x your app installs in the App Store. With the toolbox, you'll immediately know how to move forward to build better, more profitable apps.

Get The App Toolbox

Comments & Thoughts


Leave a Reply

Markdown is supported (Learn more). Your email address will not be published. Required fields are marked with *

On The Blog