Swift

Swift was started by Chris Lattner at Apple in 2010, announced in 2014 and open-sourced in 2015. It replaced Objective-C as the main language for Apple platforms, and it favours safe, expressive code that still compiles to fast native binaries.

Paradigm: Object-Functional and Beyond

What Makes Swift Special

  • Value types first. struct and enum are copied on assignment. Classes are available for shared identity, but the standard library types (Array, String) are structs.
  • Protocol-oriented programming. A protocol defines requirements, and extension can give every conforming type a default implementation. It is composition instead of a deep class hierarchy.
  • Optionals. A value that may be missing has type T?. You must unwrap it with if let, guard let, ?. or ??.
  • Enums with associated values. Each case can carry data, and switch must be exhaustive, which gives algebraic data types.
  • Closures and functional tools. Trailing closures, map, filter, reduce and key paths such as \.area are everyday tools.
  • Memory by reference counting. ARC frees class instances automatically without a garbage collector pause. Modern Swift also has structured concurrency with async/await and actors.

Example: Protocols, value semantics and functional idioms

import Foundation

protocol Shape {
    var area: Double { get }
}

struct Circle: Shape {
    var r: Double
    var area: Double { Double.pi * r * r }
}

struct Rect: Shape {
    var w: Double
    var h: Double
    var area: Double { w * h }
}

// a default behaviour for every Shape
extension Shape {
    func describe() -> String { "area " + String(format: "%.2f", area) }
}

let shapes: [any Shape] = [Circle(r: 1), Rect(w: 2, h: 3)]
print(shapes.map(\.area).reduce(0, +))     // 9.141592653589793
print(shapes[1].describe())                // area 6.00

// value semantics: b is a copy of a
var a = Rect(w: 2, h: 3)
var b = a
b.w = 10
print(a.area, b.area)                      // 6.0 30.0

// optionals instead of null
let ages = ["Ada": 36]
print(ages["Linus"] ?? -1)                 // -1

How It Works

  • Circle and Rect are structs that conform to the Shape protocol. There is no base class.
  • The extension Shape block adds describe() to every conforming type at once.
  • shapes.map(\.area).reduce(0, +) uses a key path and an operator as functions.
  • var b = a copies the struct, so changing b.w does not affect a. With classes both names would point to the same object.
  • The dictionary lookup returns an optional, and ?? supplies a fallback.

History and Where It Is Used

Swift is used for iOS, macOS, watchOS and visionOS apps (with SwiftUI and UIKit), and also for server-side code and command-line tools on Linux and Windows. The compiler is built on LLVM, and the language evolves through a public process called Swift Evolution. See also the full Swift roadmap on this site.

Learn More