enum Result { case success(Int), failure(String) }
Enum with associated values
protocol Shape { var area: Double { get } }
Protocol
extension Int { var isEven: Bool { self % 2 == 0 } }
Extension
func largest<T: Comparable>(_ a: T, _ b: T) -> T
Generic function
Errors & Concurrency
enum LoginError: Error { case wrongPassword }
Define an error
func login() throws -> User
A throwing function
do { let user = try login() } catch { print(error) }
Handle errors
func load() async throws -> Data
Asynchronous function
let data = try await load()
Call and wait
actor Counter { var value = 0 }
Actor — protects its state from data races
Tooling
swift hello.swift
Run a single file
swift package init --type executable
Create a package
swift build / swift run
Build / build and run
swift test
Run the package's tests
Cookies & your privacy
We use essential cookies to keep this site working and secure.
With your permission, we'd also like to use Google Analytics cookies to understand site traffic.
We don't use advertising or social media tracking cookies, and we honor Global Privacy Control (GPC) browser signals.
Learn more in our Privacy Policy.
Your browser is sending a GPC signal, so analytics stays off even if you accept.