Swift
Updated: May 22, 2026Categories: Languages, Mobile, Apple
Printed from:
Swift Cheatsheet
Language Overview
Swift is a modern, powerful, and intuitive programming language developed by Apple and maintained by the Swift open-source community. It is designed to be:
- Type-safe
- Fast and performant
- Expressive and concise
- Safe by default
- Supports object-oriented, protocol-oriented, and functional programming paradigms
- Cross-platform (Apple platforms, Linux, Windows, and embedded targets)
Basic Syntax
Hello World
Swift
12print("Hello, World!")
Comments
Swift
123456// Single-line comment
/*
Multi-line
comment
*/
/// Documentation comment (Markdown supported)
Data Types
Primitive Types
Swift
123456789101112131415161718// Integer Types
let int8: Int8 = 127
let int16: Int16 = 32767
let int32: Int32 = 2_147_483_647
let int64: Int64 = 9_223_372_036_854_775_807
let integer: Int = 42 // Platform-specific size
// Floating Point Types
let float: Float = 3.14159
let double: Double = 3.14159265358979
// Boolean
let boolean: Bool = true
// Character and String
let character: Character = "A"
let string: String = "Swift Programming"
Collection Types
Swift
123456789101112// Arrays
var intArray: [Int] = [1, 2, 3]
var emptyArray = [String]()
// Dictionaries
var dict: [String: Int] = ["age": 30, "year": 2026]
var emptyDict = [String: String]()
// Sets
var uniqueInts: Set<Int> = [1, 2, 3, 3, 4]
var emptySet = Set<String>()
Variables and Constants
Swift
123456789101112131415// Constants (immutable)
let pi = 3.14159
let maxLoginAttempts = 3
// Variables (mutable)
var score = 0
score += 10
// Type inference
var name = "Swift" // Inferred as String
var count = 42 // Inferred as Int
// Explicit type annotation
var explicitString: String = "Explicit"
Optionals and Nil Safety
Swift
1234567891011121314151617181920212223// Optional declaration
var optionalName: String? = nil
var definedName: String? = "John"
// Optional binding (shorthand from Swift 5.7+)
if let optionalName {
print(optionalName)
}
// Traditional optional binding
if let unwrappedName = optionalName {
print(unwrappedName)
}
// Nil-coalescing operator
let displayName = optionalName ?? "Anonymous"
// Optional chaining
let length = optionalName?.count
// Force unwrapping (use with caution)
let forcedValue = optionalName!
Operators
Arithmetic Operators
Swift
123456let sum = 10 + 5
let difference = 10 - 5
let product = 10 * 5
let quotient = 10 / 5
let remainder = 10 % 3
Comparison Operators
Swift
123456789let a = 5
let b = 10
print(a == b) // Equal to
print(a != b) // Not equal to
print(a < b) // Less than
print(a > b) // Greater than
print(a <= b) // Less than or equal to
print(a >= b) // Greater than or equal to
Logical Operators
Swift
123456let x = true
let y = false
print(x && y) // Logical AND
print(x || y) // Logical OR
print(!x) // Logical NOT
Control Structures
Conditional Statements
Swift
123456789101112131415// If-Else
if condition {
// code
} else if anotherCondition {
// code
} else {
// code
}
// if/switch as expressions (Swift 5.9+)
let label = if score >= 90 { "A" } else if score >= 80 { "B" } else { "C" }
// Ternary Conditional
let result = condition ? valueIfTrue : valueIfFalse
Switch Statements
Swift
123456789101112let value = 5
switch value {
case 1:
print("One")
case 2...5:
print("Between two and five")
case let x where x > 10:
print("Greater than ten")
default:
print("Other value")
}
Loops
Swift
1234567891011121314151617// For loop
for i in 1...5 {
print(i)
}
// While loop
var counter = 0
while counter < 5 {
print(counter)
counter += 1
}
// Repeat-While (do-while equivalent)
repeat {
// code
} while condition
Functions
Swift
123456789101112131415161718192021222324252627282930// Basic function
func greet(name: String) -> String {
return "Hello, \(name)!"
}
// Function with multiple parameters
func add(a: Int, b: Int) -> Int {
a + b // Implicit return for single-expression functions
}
// Function with default parameter
func power(base: Int, exponent: Int = 2) -> Int {
return Int(pow(Double(base), Double(exponent)))
}
// Variadic parameters
func sum(_ numbers: Int...) -> Int {
return numbers.reduce(0, +)
}
// Throwing function
func riskyOperation() throws {
// Can throw an error
}
// Typed throws (Swift 6+)
func parse() throws(ParseError) -> Int {
// Throws only ParseError
}
Closures
Swift
12345678910111213141516// Closure expression
let multiply = { (a: Int, b: Int) -> Int in
return a * b
}
// Trailing closure syntax
let numbers = [1, 2, 3, 4, 5]
let squared = numbers.map { $0 * $0 }
// Multiple trailing closures (Swift 5.3+)
UIView.animate(withDuration: 0.3) {
view.alpha = 0
} completion: { _ in
view.removeFromSuperview()
}
Object-Oriented Programming
Structs
Swift
123456789struct Point {
var x: Double
var y: Double
func distance(to other: Point) -> Double {
return sqrt(pow(x - other.x, 2) + pow(y - other.y, 2))
}
}
Classes
Swift
1234567891011121314class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
func introduce() {
print("Hi, I'm \(name)")
}
}
Inheritance
Swift
123456789class Student: Person {
var grade: Int
init(name: String, age: Int, grade: Int) {
self.grade = grade
super.init(name: name, age: age)
}
}
Protocols
Swift
12345678910111213141516171819protocol Drawable {
func draw()
}
struct Circle: Drawable {
func draw() {
print("Drawing a circle")
}
}
// Primary associated types (Swift 5.7+)
protocol Container<Item> {
associatedtype Item
var items: [Item] { get }
}
// Use with some/any
func makeContainer() -> some Container<Int> { /* ... */ }
Macros (Swift 5.9+)
Swift
123456789// Freestanding macros
let url = #URL("https://swift.org")
// Attached macros
@Observable
final class Model {
var count = 0
}
Error Handling
Swift
123456789101112131415161718192021enum NetworkError: Error {
case connectionFailed
case invalidResponse
}
func fetchData() throws {
// Potentially throwing operation
throw NetworkError.connectionFailed
}
do {
try fetchData()
} catch NetworkError.connectionFailed {
print("Connection failed")
} catch {
print("Unknown error: \(error)")
}
// Result type for explicit success/failure
func load() -> Result<Data, NetworkError> { /* ... */ }
File I/O
Swift
123456789101112import Foundation
// Writing to a file
let content = "Hello, File!"
let fileURL = URL(filePath: "/path/to/file.txt") // URL(fileURLWithPath:) still available
try? content.write(to: fileURL, atomically: true, encoding: .utf8)
// Reading from a file
if let fileContent = try? String(contentsOf: fileURL, encoding: .utf8) {
print(fileContent)
}
Concurrency
Swift
1234567891011121314151617181920212223242526272829303132333435363738394041424344// Async/Await
func fetchUserData() async throws -> User {
// Asynchronous operation
}
// Calling async code
let user = try await fetchUserData()
// Structured concurrency with task groups
try await withThrowingTaskGroup(of: User.self) { group in
for id in ids {
group.addTask { try await fetchUser(id: id) }
}
for try await user in group {
print(user)
}
}
// Async sequences
for try await line in url.lines {
print(line)
}
// Actor for safe concurrent state
actor UserCache {
private var cache = [Int: User]()
func getUser(id: Int) -> User? {
return cache[id]
}
}
// Global actors
@MainActor
final class ViewModel {
var title = ""
}
// Sendable conformance for cross-actor types
struct Message: Sendable {
let id: UUID
let text: String
}
Swift 6 Strict Concurrency
- Compile-time data-race safety is enforced under the Swift 6 language mode.
- Non-
Sendabletypes cannot cross actor boundaries. - Adopt incrementally with
-swift-version 6or per-target language mode inPackage.swift.
Memory Management
Swift
1234567891011// Weak reference to prevent retain cycles
class ViewController {
weak var delegate: ViewControllerDelegate?
}
// Unowned reference
class Customer {
let card: CreditCard
unowned let shop: Shop
}
Testing
Swift
123456789101112131415161718192021222324252627// XCTest (traditional)
import XCTest
final class MyXCTests: XCTestCase {
func testAddition() {
XCTAssertEqual(1 + 1, 2)
}
func testPerformance() {
measure {
// Code to measure performance
}
}
}
// Swift Testing (Swift 6+, cross-platform)
import Testing
@Test func addition() {
#expect(1 + 1 == 2)
}
@Test(arguments: [1, 2, 3])
func isPositive(_ value: Int) {
#expect(value > 0)
}
Popular Frameworks
- SwiftUI: Declarative UI framework across Apple platforms
- UIKit / AppKit: Imperative UI frameworks for iOS/macOS
- Combine: Reactive programming framework
- Swift Concurrency: Built-in async/await, actors, task groups
- SwiftData: Modern persistence framework built on Core Data
- Core Data: Persistence and data management
- Observation: Macro-based observation for SwiftUI (
@Observable) - Vapor: Server-side Swift framework
- Hummingbird: Lightweight server-side Swift framework
Best Practices
- Use
letby default,varonly when necessary - Prefer value types (structs) over classes
- Use optionals for potentially absent values
- Leverage type inference, but annotate public APIs
- Use protocol extensions for shared behavior
- Write small, focused functions
- Use
guardfor early returns and reducing nesting - Prefer
async/awaitover completion handlers - Mark concurrency-safe types as
Sendable - Adopt the Swift 6 language mode incrementally for data-race safety
Resources for Further Learning
- Apple Swift Documentation (developer.apple.com)
- Swift.org (official open-source site and evolution proposals)
- The Swift Programming Language book (docs.swift.org)
- Stanford CS193p (iOS Development Course)
- WWDC Swift Sessions
- Swift by Sundell
- Hacking with Swift
- Point-Free
Performance Tips
- Use value types when possible
- Avoid excessive dynamic dispatch (
final,privatehelp devirtualization) - Leverage compile-time optimizations
- Use
@inlinableand@usableFromInlinefor performance-critical library code - Profile and optimize with Instruments
- Consider
borrowing/consumingparameter ownership modifiers for performance-sensitive APIs
Swift Package Manager
Bash
123456789101112131415161718# Create a new package
swift package init --type library
# Add a dependency (Swift 5.8+)
swift package add-dependency https://github.com/example/library.git --from 1.0.0
# Add a product dependency to a target
swift package add-target-dependency LibraryName MyTarget
# Build the package
swift build
# Run tests (includes Swift Testing and XCTest)
swift test
# Generate documentation with DocC
swift package generate-documentation
Package.swift Example
Swift
1234567891011121314151617// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "MyLibrary",
platforms: [.macOS(.v14), .iOS(.v17)],
products: [
.library(name: "MyLibrary", targets: ["MyLibrary"]),
],
dependencies: [],
targets: [
.target(name: "MyLibrary"),
.testTarget(name: "MyLibraryTests", dependencies: ["MyLibrary"]),
],
swiftLanguageModes: [.v6]
)
Continue Learning
Discover more cheatsheets to boost your productivity