Polyglot
Languages Swift stdlib
Swift § stdlib

Standard library

The Swift standard library admits the principal types and protocols — Numeric (Int, Double, etc.), String, Sequence/Collection, Optional/Result, Array/Dictionary/Set, Range. The Foundation framework (built on top) admits substantial additional functionality — Date, URL, UUID, Data, URLSession, FileManager, NotificationCenter, UserDefaults, Bundle, DateFormatter, etc. The Swift Numerics and Swift Collections packages admit substantial extensions. For domain-specific work, Apple’s frameworks (Combine, SwiftUI, SwiftData, RealityKit) admit substantial functionality. The combination — the substantial standard library, the rich Foundation framework, the cross-platform open-source ecosystem (Linux, Windows), the platform-specific Apple frameworks — is the substance of Swift’s runtime library.

This tour points out the principal types and protocols.

Numeric types

Int, Int8, Int16, Int32, Int64
UInt, UInt8, UInt16, UInt32, UInt64
Float, Double
Float16, Float80                                   // platform-dependent

Bool

// Conversions:
Int(3.7)                                           // 3 (truncating)
Double(5)
String(42)
Int("42")                                          // Optional<Int>

// Math (require import Foundation):
abs(-5), max(3, 7), min(3, 7)
3.0.squareRoot()
4.0.rounded()                                      // 4.0
4.5.rounded(.up)                                   // 5.0
pow(2.0, 10.0)                                     // 1024.0

Sequence and Collection

The principal protocols:

protocol Sequence {
    associatedtype Element
    func makeIterator() -> Iterator
}

protocol Collection: Sequence {
    associatedtype Index: Comparable
    var startIndex: Index { get }
    var endIndex: Index { get }
    subscript(_: Index) -> Element { get }
    func index(after: Index) -> Index
}

The substantial method library (map, filter, reduce, sorted, etc.) is provided through these protocols.

Array, Dictionary, Set

Treated in Data structures.

Optional, Result

Treated in Optionals and Error handling.

String

Treated in Strings.

Range

let r1 = 0..<10
let r2 = 0...10
let r3 = "a"..."z"

r1.contains(5)
r1.lowerBound
r1.upperBound

Foundation

The Foundation framework admits substantial additional functionality:

import Foundation

Date

let now = Date()                                   // current time
let now = Date.now                                  // alias

now.timeIntervalSince1970                          // Double seconds since epoch
now.timeIntervalSinceNow                           // Double seconds (negative for past)

// Arithmetic:
let later = now.addingTimeInterval(60)             // 60 seconds later
let diff = later.timeIntervalSince(now)            // 60.0

// Distance and duration:
let oneDay = 24 * 60 * 60.0
let yesterday = now.addingTimeInterval(-oneDay)

// Comparison:
later > now                                        // true
later == now                                       // false

// Format:
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.string(from: now)

// Modern (Swift 5.5+):
now.formatted(date: .complete, time: .complete)
now.formatted(.iso8601)
now.formatted(.dateTime.year().month().day())

For substantial date arithmetic, Calendar:

let cal = Calendar.current
let nextWeek = cal.date(byAdding: .day, value: 7, to: now)
let isLeap = cal.isDateInToday(now)
let components = cal.dateComponents([.year, .month, .day], from: now)

TimeInterval and Duration

let interval: TimeInterval = 30                    // alias for Double seconds

// Modern (Swift 5.7+):
let duration: Duration = .seconds(30)
let ms: Duration = .milliseconds(500)
let combined = duration + ms

URL

let url = URL(string: "https://example.com/path?q=1")!
let fileURL = URL(fileURLWithPath: "/etc/hosts")
let fileURL = URL(filePath: "/etc/hosts")          // newer

url.host                                           // "example.com"
url.path                                           // "/path"
url.query                                          // "q=1"
url.scheme                                         // "https"
url.lastPathComponent

let combined = url.appendingPathComponent("more")
let parent = url.deletingLastPathComponent()

URLComponents

var components = URLComponents()
components.scheme = "https"
components.host = "api.example.com"
components.path = "/users"
components.queryItems = [
    URLQueryItem(name: "page", value: "2"),
    URLQueryItem(name: "limit", value: "50"),
]

let url = components.url
// "https://api.example.com/users?page=2&limit=50"

UUID

let id = UUID()                                    // random
print(id.uuidString)                               // "ABC1234E-5678-..."

let parsed = UUID(uuidString: "ABC1234E-5678-...")  // Optional<UUID>

Data

The Foundation Data is a byte container:

let bytes: [UInt8] = [0xff, 0x00, 0x01]
let data = Data(bytes)

let fromString = "hello".data(using: .utf8)        // Optional<Data>
let toString = String(data: data, encoding: .utf8)

let written = try data.write(to: fileURL)
let read = try Data(contentsOf: fileURL)

// Manipulation:
data.count
data[0]                                            // UInt8
data.subdata(in: 0..<10)
data + otherData                                    // concatenation

URLSession

HTTP client:

let session = URLSession.shared

// Async (Swift 5.5+):
let (data, response) = try await session.data(from: url)

// With request:
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try JSONEncoder().encode(payload)

let (data, response) = try await session.data(for: request)

// Bytes / lines:
let (bytes, _) = try await session.bytes(from: url)
for try await line in bytes.lines {
    print(line)
}

JSON

struct User: Codable {
    let id: Int
    let name: String
}

let user = User(id: 1, name: "Alice")

// Encode:
let json = try JSONEncoder().encode(user)
let pretty = JSONEncoder()
pretty.outputFormatting = [.prettyPrinted, .sortedKeys]
let prettyJSON = try pretty.encode(user)

// Decode:
let decoded = try JSONDecoder().decode(User.self, from: json)

PropertyListEncoder

let plist = try PropertyListEncoder().encode(user)
let decoded = try PropertyListDecoder().decode(User.self, from: plist)

XML

The standard library does not include an XML parser; XMLParser is admitted in Foundation but is event-based (rarely used). For substantial XML, gems (e.g., SWXMLHash) are conventional.

Number formatting

let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale(identifier: "en_US")
formatter.string(from: 1234.56)                    // "$1,234.56"

// Modern (Swift 5.5+):
let n = 1234567.89
n.formatted()                                      // "1,234,567.89"
n.formatted(.currency(code: "USD"))                // "$1,234,567.89"
n.formatted(.percent)
n.formatted(.number.precision(.fractionLength(2)))

Locale

let current = Locale.current
let custom = Locale(identifier: "ja_JP")

current.identifier                                 // "en_US" (or similar)
current.language.languageCode
current.region?.identifier

NotificationCenter

Pub-sub for events:

extension Notification.Name {
    static let userDidLogin = Notification.Name("userDidLogin")
}

// Subscribe:
NotificationCenter.default.addObserver(
    forName: .userDidLogin,
    object: nil,
    queue: .main
) { notification in
    handleUserLogin(notification.userInfo)
}

// Or:
let observation = NotificationCenter.default.addObserver(
    forName: .userDidLogin,
    object: nil,
    queue: .main
) { _ in /* ... */ }

// Unsubscribe:
NotificationCenter.default.removeObserver(observation)

// Post:
NotificationCenter.default.post(
    name: .userDidLogin,
    object: nil,
    userInfo: ["user": user]
)

// Async (Swift 5.5+):
for await notification in NotificationCenter.default.notifications(named: .userDidLogin) {
    handle(notification)
}

UserDefaults

Key-value storage:

let defaults = UserDefaults.standard

defaults.set("Alice", forKey: "username")
defaults.set(true, forKey: "isFirstLaunch")
defaults.set(42, forKey: "count")

let username = defaults.string(forKey: "username")  // Optional<String>
let isFirst = defaults.bool(forKey: "isFirstLaunch")
let count = defaults.integer(forKey: "count")

defaults.removeObject(forKey: "username")

Bundle

Resource access:

Bundle.main                                        // main app bundle
Bundle.module                                      // SPM target's bundle

let url = Bundle.main.url(forResource: "config", withExtension: "json")
let path = Bundle.main.path(forResource: "image", ofType: "png")
let info = Bundle.main.infoDictionary

Process

let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/git")
process.arguments = ["status"]

let pipe = Pipe()
process.standardOutput = pipe

try process.run()
process.waitUntilExit()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)

FileManager

Treated in I/O.

Combine

Apple’s reactive framework:

import Combine

class ViewModel: ObservableObject {
    @Published var query: String = ""
    @Published var results: [Result] = []

    private var cancellables: Set<AnyCancellable> = []

    init() {
        $query
            .debounce(for: .milliseconds(300), scheduler: DispatchQueue.main)
            .removeDuplicates()
            .sink { [weak self] query in
                self?.search(query)
            }
            .store(in: &cancellables)
    }
}

let publisher = Just(42)                           // single-value publisher
let publisher = [1, 2, 3].publisher                // sequence publisher
let publisher = NotificationCenter.default
    .publisher(for: .userDidLogin)

publisher
    .map { /* ... */ }
    .filter { /* ... */ }
    .receive(on: DispatchQueue.main)
    .sink { value in /* ... */ }
    .store(in: &cancellables)

For substantial reactive patterns; the contemporary alternative for some patterns is AsyncSequence.

Apple frameworks

For Apple platforms:

SwiftUI

import SwiftUI

struct ContentView: View {
    @State private var counter: Int = 0

    var body: some View {
        VStack {
            Text("Counter: \(counter)")
            Button("Increment") {
                counter += 1
            }
        }
    }
}

SwiftData (iOS 17+, macOS 14+)

import SwiftData

@Model
final class TodoItem {
    var title: String
    var isDone: Bool
    var createdAt: Date

    init(title: String, isDone: Bool = false) {
        self.title = title
        self.isDone = isDone
        self.createdAt = .now
    }
}

@MainActor
let container = try ModelContainer(for: TodoItem.self)
let context = container.mainContext

context.insert(TodoItem(title: "Buy milk"))
try context.save()

let descriptor = FetchDescriptor<TodoItem>(
    predicate: #Predicate { !$0.isDone },
    sortBy: [SortDescriptor(\.createdAt)]
)
let active = try context.fetch(descriptor)

UIKit / AppKit

For application UI on iOS / macOS respectively. Conventional for substantial application development; SwiftUI is the modern alternative.

Foundation Networking, Crypto, etc.

import CryptoKit

let data = "hello".data(using: .utf8)!
let hash = SHA256.hash(data: data)
print(hash.compactMap { String(format: "%02x", $0) }.joined())
// "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"

let key = SymmetricKey(size: .bits256)
let sealed = try AES.GCM.seal(data, using: key)

Swift Numerics

import Numerics

let z = Complex<Double>(2, 3)                     // 2 + 3i
let modulus = z.magnitude

// Real protocol — admits real-valued operations on Float, Double, Float80:
extension Real {
    func mySquare() -> Self { self * self }
}

Swift Collections

import Collections

var deque: Deque<Int> = []
deque.append(1)
deque.prepend(0)

let ordered: OrderedDictionary<String, Int> = ["c": 1, "a": 2, "b": 3]
// Maintains insertion order

let orderedSet: OrderedSet<Int> = [3, 1, 4, 1, 5]
// Maintains insertion order, unique

var heap: Heap<Int> = []
heap.insert(5)
heap.insert(2)
heap.insert(8)
let smallest = heap.popMin()                      // 2

The Collections package admits substantial additional data structures.

Swift Async Algorithms

import AsyncAlgorithms

// merge:
for await event in merge(stream1, stream2, stream3) {
    handle(event)
}

// chunked:
for await batch in stream.chunks(ofCount: 10) {
    process(batch)
}

// debounced:
for await query in queries.debounce(for: .milliseconds(300)) {
    search(query)
}

Swift Argument Parser

import ArgumentParser

@main
struct MyTool: ParsableCommand {
    @Option(name: .shortAndLong, help: "The output path")
    var output: String

    @Flag(name: .shortAndLong, help: "Verbose output")
    var verbose: Bool = false

    @Argument(help: "The input file")
    var input: String

    mutating func run() throws {
        // ...
    }
}

Common patterns

Date arithmetic

let today = Date.now
let inAWeek = today.addingTimeInterval(7 * 86400)

let cal = Calendar.current
let nextMonth = cal.date(byAdding: .month, value: 1, to: today)!
let yearStart = cal.date(from: cal.dateComponents([.year], from: today))!

URL building

var components = URLComponents(string: "https://api.example.com/users")!
components.queryItems = [
    URLQueryItem(name: "page", value: "1"),
    URLQueryItem(name: "limit", value: "50"),
]
let url = components.url!

JSON request

struct CreateUser: Codable {
    let name: String
    let email: String
}

let payload = CreateUser(name: "Alice", email: "a@b.c")
let data = try JSONEncoder().encode(payload)

var request = URLRequest(url: apiURL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = data

let (responseData, _) = try await URLSession.shared.data(for: request)
let result = try JSONDecoder().decode(User.self, from: responseData)

NotificationCenter pattern

extension Notification.Name {
    static let dataUpdated = Notification.Name("dataUpdated")
}

// Publisher (post):
NotificationCenter.default.post(name: .dataUpdated, object: self)

// Subscriber (async):
Task {
    for await _ in NotificationCenter.default.notifications(named: .dataUpdated) {
        await refresh()
    }
}

UserDefaults wrapper

@propertyWrapper
struct UserDefault<T> {
    let key: String
    let defaultValue: T

    var wrappedValue: T {
        get {
            UserDefaults.standard.object(forKey: key) as? T ?? defaultValue
        }
        set {
            UserDefaults.standard.set(newValue, forKey: key)
        }
    }
}

class Settings {
    @UserDefault(key: "username", defaultValue: "") var username: String
    @UserDefault(key: "theme", defaultValue: "light") var theme: String
}

Format dates and numbers

let date = Date.now
let dateString = date.formatted(.dateTime.year().month(.abbreviated).day())
// "Jan 15, 2026"

let n = 1234.56
let currencyString = n.formatted(.currency(code: "USD"))
// "$1,234.56"

File reading

import Foundation

let url = URL(filePath: "/path/to/file.txt")
let contents = try String(contentsOf: url, encoding: .utf8)

// Or:
let data = try Data(contentsOf: url)
let text = String(data: data, encoding: .utf8) ?? ""

Treated in I/O.

Bundle resource

guard let url = Bundle.main.url(forResource: "config", withExtension: "json") else {
    fatalError("config.json not found in bundle")
}

let data = try Data(contentsOf: url)
let config = try JSONDecoder().decode(Config.self, from: data)

A note on the conventional discipline

The contemporary Swift standard-library advice:

  • Use the standard library for primary types and protocols.
  • Import Foundation for routine functionality (Date, URL, UUID, Data, JSON, etc.).
  • Use Swift Collections for Deque, OrderedDictionary, Heap.
  • Use Swift Numerics for Complex, advanced numeric protocols.
  • Use Swift Async Algorithms for substantial async patterns.
  • Use Swift Argument Parser for CLI tools.
  • Use Combine for reactive patterns; async/await for sequential async.
  • Use SwiftUI / SwiftData for modern Apple-platform application work.
  • Use URLSession for HTTP (with async API).
  • Use JSONEncoder / JSONDecoder with Codable for serialisation.
  • Use formatted() for substantial number/date formatting.
  • Use Bundle.module for SPM resources.

The combination — substantial standard-library types and protocols, the Foundation framework, the cross-platform open-source extensions, the substantial Apple-framework integration — is the substance of Swift’s runtime library. The discipline produces concise, expressive code with substantial built-in functionality across the principal Swift use cases.