swift-logo.png

Introduction to Swift

Swift debuted in 2014. What's it like?

Overview

Swift

For documentation, sample code, books, videos, and related things, see Apple's Swift Resources.

Getting Started

You can write Swift code

Basic Command Line Scripts

Let's write and run some little scripts. Fire up your favorite editor and continue the tradition:

hello.swift
print("Hello, world")
$ swift hello.swift
Hello, world

Move on to using for-loops and string interpolation:

triple.swift
for c in 1...100 {
    for b in 1..<c {
        for a in 1..<b {
            if a * a + b * b == c * c {
                print("(\(a), \(b), \(c))")
            }
        }
    }
}
$ swift triple.swift
(3, 4, 5)
(6, 8, 10)
(5, 12, 13)
(9, 12, 15)
(8, 15, 17)
.
.
.
(35, 84, 91)
(57, 76, 95)
(65, 72, 97)
(60, 80, 100)
(28, 96, 100)

And then work with command line arguments, while-loops, and tuples:

fib.swift
// Writes Fibonacci numbers up to and including the first commandline argument.

var n = Int(CommandLine.arguments[1]) ?? 0

var (a, b) = (0, 1)
while b <= n {
    print(b, terminator: " ")
    (a, b) = (b, a+b)
}
print("")
$ swift fib.swift 300
1 1 2 3 5 8 13 21 34 55 89 144 233
$ swift fib.swift dog

$ swift fib.swift
fatal error: Array index out of range

The REPL

The XCode Playground

Declarations and Types

Expressions

Statements

Functions

Closures

Structs

Classes and OOP

Enums

Protocols

Generics