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.
structandenumare copied on assignment. Classes are available for shared identity, but the standard library types (Array,String) are structs. - Protocol-oriented programming. A
protocoldefines requirements, andextensioncan 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 withif let,guard let,?.or??. - Enums with associated values. Each case can carry data, and
switchmust be exhaustive, which gives algebraic data types. - Closures and functional tools. Trailing closures,
map,filter,reduceand key paths such as\.areaare everyday tools. - Memory by reference counting. ARC frees class instances automatically without a garbage collector pause. Modern Swift also has structured concurrency with
async/awaitand 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
CircleandRectare structs that conform to theShapeprotocol. There is no base class.- The
extension Shapeblock addsdescribe()to every conforming type at once. shapes.map(\.area).reduce(0, +)uses a key path and an operator as functions.var b = acopies the struct, so changingb.wdoes not affecta. 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.