Alex headshot

AlBlue’s Blog

Macs, Modularity and More

Swift - introducing the REPL

2014 Swift Mac Osx

In this new series, we’ll be looking at Apple’s new Swift programming language, and how you can start mastering Swift. No prior experience of Apple technologies is assumed, though you will have to have a recent Mac OSX and Xcode 6.0.1 or above installed to follow through the exercises. You can also subscribe to just these posts by following the Swift tag feed.

What is Swift?

Swift is a statically typed object-oriented/functional hybrid programming language. It’s a little like Scala (except that it has a much brighter future) and is compiled down to platform-specific executable code rather than using a VM like Java or C#. It was created from the LLVM team (who produced clang, the C++/Objective-C compiler used by all Apple and iOS devices currently) and a lot of the experience in those languages was distilled into Swift. Because it can compile down to bare metal, Swift provides ways of representing both object types with pass-by-reference semantics as well as struct types with pass-by-value semantics. As a result it should be equally capable when used for displaying user interfaces and for implementing highly performant back-end services.

Swift does have a few aspects which make it more immediately valuable than C and Objective-C; firstly, although the language is statically typed, variables can use type inference to avoid having to use the predefined type everywhere, as is done in C. This makes the language feel much more like a dynamic language like JavaScript but with a much more performant runtime. Secondly, Swift has an interpreter (called swift) that can be used to learn the language and prototype spike solutions. And as if that wasn’t enough, Xcode 6 comes with a feature called Playgrounds that provides an interactive GUI along with interim results of code execution, and the ability to graph results over time. We’ll look at that next time.

Using the Swift REPL

To run a Swift program, type xcrun swift from a Terminal console. You’ll see a pop-up show the prompt:

```sh Welcome to Swift $ xcrun swift Welcome to Swift! Type :help for assistance. 1>


<img class="center" src="/2014/09/WelcomeToSwift.gif" title="Welcome to Swift" >

<i><b>Note</b>: if the swift REPL complains that OSX is not supported in Xcode
6.0, then run with an `-sdk` argument that points to an iPhoneSimulator.sdk
location instead, such as <code>xcrun swift -sdk
/Applications/&#x200B;Xcode.app/&#x200B;Contents/&#x200B;Developer/&#x200B;Platforms/&#x200B;iPhoneSimulator.platform/&#x200B;Developer/&#x200B;SDKs/&#x200B;iPhoneSimulator.sdk</code></i>

The `1>` prompt is the input prompt; expressions and statements typed here will
can be executed on demand. Typing in a series of expressions results in output
being seen:

```sh Simple expressions and statements
 1> "Hello " + "Swift!"
$R0: String = "Hello Swift!"
 2> 3+4
$R1: Int = 7
 3> "D\(7-5)"
$R2: String = "D2"
 4> 3.141
$R3: Double = 3.141
 5> [1,2,3,4,5]
$R4: [Int] = 5 values {
  [0] = 1
  [1] = 2
  [2] = 3
  [3] = 4
  [4] = 5
}
 6> ["name":"AlBlue's Blog","url":"http://alblue.bandlem.com/Tag/swift/"]
$R5: [String : String] = {
  [0] = {
    key = "name"
    value = "AlBlue's Blog"
  }
  [1] = {
    key = "url"
    value = "http://alblue.bandlem.com/Tag/swift/"
  }
}

The $Rn values are intermediate variables that are used for storing the results. These can be recalled by using the variable in an expression. Note that Swift has detected the type of each of these and indicates what the type is in the output, including Bool, String, Int (various sizes), Double (and Float), Array and Dictionary. These are type-safe, and cannot be used to mix values of a different type:

```sh Type checked collections 7> $R4 + [ “once”, “I”, “caught”, “a”, “fish”, “alive” ] error: cannot invoke ‘+’ with an argument list of type ‘(@lvalue Double, $T8)’ $R4 + [ “once”, “I”, “caught”, “a”, “fish”, “alive” ] ~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 8> $R5[“year”] = 2014 error: ‘@lvalue $T5’ is not identical to ‘(String, String)’ $R5[“year”] = 2014


<h2>Variables and Constants</h2>

It's possible to create variables with the var keyword and constants with the
let keyword (much like `var` and `val` in Scala, non-final and `final` in Java
or non-const and `const` in C/C++). These can be defined with or without an
explicit type. As with other functional programming languages, the style in
Swift is to have the variable first followed by the type, like `a:Int`, instead
of C and Java style syntax which is `Int a`. The reason for this difference is
that it permits the type to be optional; it's much easier to parse `a(:Int)?`
than it is to parse `(Int)? a`.

```sh Variables and Constants
 9> let pi_ish = 3.141
pi_ish: Double = 3.141
10> pi_ish = 3
error: cannot assign to 'let' value 'pi_ish'
pi_ish = 3
~~~~~~ ^
11> var today = 2014_09_13
today: Int = 20140913
12> today = 2014_09_14
today: Int = 20140914
13> let anInt = 1
anInt: Int = 1
14> let aDouble: Double = 1
aDouble: Double = 1
15> let aByte: Int8 = 0x7f
aByte: Int8 = 127
16> let anUnsignedByte: UInt8 = 0xff
anUnsignedByte = 255

Note that an underscore is allowed in numeric values to make it easier to read, and hexadecimal values can be specified as well. By changing what the type of the variable is, the resulting variables will take up a different amount of space at run-time, which if allocating an array of thousands of bytes will make a difference whether each byte takes up 8 bits or takes up 32 bits.


That’s a taster for this week; in next week’s episode, we’ll look at playgrounds in Swift. To subscribe to this series, add the Swift tag feed to your reader.