Menu

Swift Cheat Sheet

Last updated

Hello World & basics

Swift needs no boilerplate at top level - a single line runs.

OperationSyntax
Print a lineprint("Hello, World!")
Print without newlineprint("Hi", terminator: "")
String interpolationprint("Hi \(name)")
Comment// this is a comment
Multi-line comment/* ... */
Import a moduleimport Foundation
Run a fileswift run or swift main.swift

Variables (let / var) & types

Use let for constants and var for mutable values; types are usually inferred.

OperationSyntax
Constantlet age = 30
Variablevar count = 0
Explicit typelet name: String = "Ada"
Basic typesInt, Double, String, Bool, Character
Type conversionDouble(i), String(n), Int("42")
Tuplelet pair = (1, "a")
Type aliastypealias ID = Int
Check typevalue is String, value as? String

Optionals

Optionals model the possible absence of a value; unwrap before use.

OperationSyntax
Declare optionalvar name: String? = nil
Optional bindingif let n = name { ... }
Guard unwrapguard let n = name else { return }
Nil-coalescinglet n = name ?? "default"
Optional chaininguser?.address?.city
Force unwrap (unsafe)name!
Implicitly unwrappedvar name: String!
Map over optionalname.map { $0.count }

Strings

Strings are value types with full Unicode support.

OperationSyntax
Lengths.count
Uppercase / lowercases.uppercased(), s.lowercased()
Concatenate"foo" + "bar"
Interpolation"Total: \(price)"
Containss.contains("ell")
Has prefix / suffixs.hasPrefix("he")
Splits.split(separator: ",")
Replaces.replacingOccurrences(of: "a", with: "b")
Multi-line string""" ... """

Collections (Array, Dictionary, Set)

Three core collection types, all value types.

OperationSyntax
Array literalvar nums = [1, 2, 3]
Appendnums.append(4)
Access / countnums[0], nums.count
Map / filternums.map { $0 * 2 }, nums.filter { $0 > 1 }
Dictionary literalvar ages = ["Ada": 30]
Dictionary accessages["Ada"] returns an optional
Set literalvar ids: Set = [1, 2, 3]
Insert into setids.insert(4)
Iterate dictionaryfor (k, v) in ages { ... }

Control flow

Conditions need no parentheses; switch must be exhaustive.

OperationSyntax
If / elseif x > 0 { ... } else { ... }
Ternarylet r = x > 0 ? "pos" : "neg"
Switchswitch n { case 1: ...; default: ... }
Switch with rangecase 1...5: ...
For-in loopfor i in 0..<10 { ... }
For-in over arrayfor item in items { ... }
While loopwhile x < 100 { ... }
Repeat-whilerepeat { ... } while x < 100
Break / continuebreak, continue

Functions & closures

Functions have labeled parameters; closures are self-contained code blocks.

OperationSyntax
Define a functionfunc add(a: Int, b: Int) -> Int { a + b }
External labelfunc greet(to name: String) { ... }
Default parameterfunc greet(name: String = "World") { ... }
Variadic parameterfunc sum(_ nums: Int...) -> Int { ... }
Multiple returns (tuple)func bounds() -> (min: Int, max: Int) { ... }
Closure expressionlet f = { (x: Int) -> Int in x * x }
Trailing closurenums.map { $0 * 2 }
Shorthand arguments{ $0 + $1 }

Structs vs classes

Structs are value types (copied); classes are reference types (shared).

OperationSyntax
Define a structstruct Point { var x: Int; var y: Int }
Define a classclass Person { var name: String }
Class initializerinit(name: String) { self.name = name }
Create instancelet p = Point(x: 1, y: 2)
Mutating struct methodmutating func move() { x += 1 }
Class methodfunc greet() { ... }
Inheritance (class only)class Student: Person { ... }
Computed propertyvar area: Int { width * height }
Static memberstatic let shared = Manager()

Enums

Enums group related values and can carry associated data.

OperationSyntax
Define an enumenum Direction { case north, south }
Use a caselet d = Direction.north
Switch on enumswitch d { case .north: ... }
Raw valuesenum Status: Int { case ok = 200 }
Access raw valueStatus.ok.rawValue
Init from raw valueStatus(rawValue: 200)
Associated valuescase result(Int, String)
Methods on enumsfunc label() -> String { ... }

The Swift syntax you reach for most, on one page. This Swift cheat sheet is a quick reference for the core language - constants and variables, optionals, strings, collections, control flow, functions and closures, plus the structs, classes, and enums you build iOS and macOS apps with.

Everything here is standard Swift and compiles with the official toolchain. Copy what you need, or try every snippet live in the Swift playground - no Xcode required.

Swift cheat sheet FAQ

Is this Swift cheat sheet free?
Yes. This Swift cheat sheet is completely free, with no sign-up required. Bookmark it and come back whenever you need to look up an optional pattern, closure syntax, or collection method.
How do I unwrap an optional in Swift?
An optional may hold a value or nil, so you unwrap it before use. The safe ways are optional binding (if let n = name { ... }), a guard let at the top of a function, the nil-coalescing operator (name ?? "default"), and optional chaining (user?.name). Force unwrapping with name! works but crashes if the value is nil, so reach for it only when you are certain.
What is the difference between a struct and a class in Swift?
A struct is a value type: assigning or passing it makes a copy, so changes do not affect the original. A class is a reference type: copies share the same instance, and only classes support inheritance. Apple's guidance is to prefer structs by default and use a class when you need shared mutable state or inheritance.
Can I practice Swift online?
Yes. Open the Swift playground to run any snippet from this cheat sheet in your browser - no Xcode to install. When you want structure, Coddy's free interactive Swift course takes you from optionals and collections to structs, classes, and enums step by step.
Is this cheat sheet good for beginners?
Yes. It is organized from the most common topics (variables, optionals, control flow) down to advanced ones (closures, structs vs classes, enums), so you can use the top sections on day one and grow into the rest.
Coddy programming languages illustration

Learn Swift with Coddy

GET STARTED