Swift Cheat Sheet
A searchable reference of common Swift 5 syntax and what each snippet does.
| Snippet | What it does |
|---|---|
print("Hello, world!") | Print a value or message to the console. |
let name = "Ada" | Declare a constant with let; its value is fixed once set. |
var count = 0 | Declare a variable with var whose value can change later. |
let age: Int = 30 | Type annotation gives an explicit type, here Int for a whole number. |
let pi: Double = 3.14159 | Store a Double, a double-precision floating-point number. |
let title: String = "Swift" | Store a String, a sequence of text characters. |
let isReady: Bool = true | Store a Bool that is either true or false. |
let n = 42 | Type inference picks Int from the literal, so the annotation is optional. |
let greeting = "Hi, \(name)" | Insert a value into a string using interpolation. |
// this is a comment | Write a note the compiler ignores; use /* and */ for a block comment. |
let text = """multi-line""" | Triple double-quotes create a multi-line string literal. |
var middleName: String? | A type followed by ? is optional and may hold a value or nil. |
if let name = middleName { use(name) } | Optional binding unwraps safely and runs the block only when it is not nil. |
guard let name = middleName else { return } | Exit early unless the optional has a value, keeping name in scope after. |
let shown = middleName ?? "N/A" | The nil-coalescing operator supplies a default when the optional is nil. |
let forced = middleName! | Force unwrap reads the wrapped value and crashes if it is nil, so use it sparingly. |
let len = middleName?.count | Optional chaining returns nil for the whole expression if any link is nil. |
if let a = x, let b = y { use(a, b) } | Bind several optionals in one if statement, separated by commas. |
var nums = [1, 2, 3] | An array is an ordered list of values of the same type. |
nums.append(4) | Add an element to the end of an array. |
var ages = ["Ada": 36] | A dictionary stores key-value pairs with fast lookup by key. |
var seen: Set<Int> = [1, 2, 3] | A set is an unordered collection of unique values. |
for n in nums { print(n) } | Loop over every element in a collection. |
nums.map { $0 * 2 } | Transform each element and return a new array. |
nums.filter { $0 > 1 } | Keep only the elements that satisfy a condition. |
nums.reduce(0, +) | Combine all elements into a single value. |
nums.sorted() | Return a new array sorted in ascending order. |
nums.first | Get the first element as an optional, or nil when the collection is empty. |
nums.count | The number of elements in the collection. |
if x > 0 { a() } else { b() } | Run one block or another based on a condition. |
switch x { case 1: a(); default: b() } | Match a value against several cases; a switch must be exhaustive. |
for i in 0..<5 { print(i) } | Loop a fixed number of times over a range. |
while x > 0 { x -= 1 } | Repeat the body while a condition stays true. |
repeat { x -= 1 } while x > 0 | Run the body once, then repeat while the condition holds. |
let sign = x > 0 ? "pos" : "neg" | The ternary operator picks between two values based on a condition. |
for i in 1...5 { } | A closed range with ... includes both endpoints. |
let r = 0..<5 | A half-open range with ..< includes the start but not the end. |
func greet() { print("Hi") } | Define a reusable function with the func keyword. |
func sq(_ n: Int) -> Int { return n * n } | Declare a return type after -> and hand back a value with return. |
func move(to point: Int) { } | A parameter can have an external label (to) that differs from its internal name (point). |
func greet(name: String = "friend") { } | A default value lets callers omit that argument. |
func sum(_ nums: Int...) -> Int { 0 } | A variadic parameter accepts zero or more values as an array. |
let add = { (a: Int, b: Int) in a + b } | A closure is a self-contained block of code you can store and pass around. |
nums.forEach { print($0) } | A trailing closure is written after the parentheses when it is the last argument. |
func apply(_ f: (Int) -> Int) { } | A higher-order function takes or returns another function. |
struct Point { var x: Int; var y: Int } | A struct is a value type that is copied on assignment. |
class Animal { var name = "" } | A class is a reference type shared by reference, not copied. |
enum Suit { case hearts, spades } | An enum defines a type with a fixed set of named cases. |
enum Res { case ok(Int); case fail(String) } | Enum cases can carry associated values of different types. |
protocol Drawable { func draw() } | A protocol is a contract of requirements a type can adopt. |
extension Int { func doubled() -> Int { self * 2 } } | An extension adds methods or properties to an existing type. |
var area: Int { width * height } | A computed property calculates its value each time it is read. |
guard x > 0 else { return } | guard exits the current scope early when a condition fails. |
init(x: Int) { self.x = x } | An initializer sets up the stored properties of a new instance. |
class Dog: Animal { } | A class can inherit from a superclass with a colon. |
static let shared = Store() | A static member belongs to the type itself, shared across instances. |
No snippets match your search.
Runs entirely in your browser. Nothing you type is sent anywhere; open DevTools and watch the Network tab to verify zero requests.
What this tool does
This is a searchable quick reference for the Swift syntax you reach for every day, from declaring constants and variables to unwrapping optionals, looping over collections, writing functions and closures, and modeling data with structs, enums, and protocols. Each row pairs a small snippet with a plain-English note on what it does. Type in the filter box to search across both columns, or tap a category button to focus on one area. The whole list is built into the page, so it works offline and sends nothing anywhere.
How to use it
Start typing in the Filter box. Entering optional
surfaces if let, guard let, and the nil-coalescing
operator; entering map or filter jumps to the collection
transforms; entering struct shows how value types are declared. The
category buttons (Basics, Optionals, Collections, Control flow,
Functions, Types) narrow the table to one area and combine with the text filter, so
you can pick Types and type protocol to see just that. Clear the box to
see the full sheet again.
Common use cases
- Recalling the exact syntax for a feature you use rarely, like a variadic parameter or a computed property.
- Copying a correct snippet into your editor instead of guessing at Swift syntax.
- Teaching a teammate the difference between a
structand aclass, or betweenletandvar. - Looking up how optional chaining and nil coalescing combine to give a safe default.
- Reviewing core Swift before an interview or a new project.
Common pitfalls
- Force-unwrapping a nil optional. Adding a trailing
!to an optional that turns out to be nil crashes at runtime. Preferif let,guard let, or the??operator to handle the empty case safely. - Confusing value and reference types. A
structis copied on assignment while aclassis shared, so mutating a copy of a struct never affects the original. Reach for a class only when you truly need shared, referenced state. - Forgetting a switch must be exhaustive. A
switchover an enum has to cover every case or include adefault, or the code will not compile. Add the missing cases rather than reaching for default too quickly. - Overusing force operators. The
!force-unwrap andtry!bypass Swift safety checks and trade a clear error for a crash. Keep them out of production paths and let the compiler guide you to a safe alternative.
Frequently asked questions
- What is an optional in Swift?
- An optional is a type that either holds a value or holds nil, written by adding a question mark to the type, such as String?. It forces you to handle the empty case before using the value, which prevents the null-reference crashes common in other languages. You unwrap it safely with if let, guard let, optional chaining, or the nil-coalescing operator.
- What is the difference between a struct and a class in Swift?
- A struct is a value type: assigning it or passing it to a function makes a copy, so each holder has its own independent data. A class is a reference type: assignment shares one instance, so a change made through one variable is visible through another. Classes also support inheritance and deinitializers, while structs are simpler and are the recommended default in Swift for most models.
- What does guard let do in Swift?
- guard let unwraps an optional and binds it to a name that stays in scope for the rest of the function. If the value is nil, the else block runs and must leave the current scope, usually with return, break, or continue. It keeps the main path unindented and handles the failure case up front, which is clearer than deeply nested if let checks.
- What is a trailing closure in Swift?
- When the last parameter of a function is a closure, Swift lets you write that closure after the closing parenthesis instead of inside it. This reads more like built-in syntax and is common with collection methods such as map, filter, and sorted. If the closure is the only argument you can drop the parentheses entirely.
- What is a protocol in Swift?
- A protocol is a contract that lists methods, properties, and other requirements a type must provide. Any struct, class, or enum can adopt a protocol and then be used wherever that protocol is expected, which is how Swift models shared behavior without inheritance. Protocols can also be extended to supply default implementations.
- What is the difference between let and var in Swift?
- let declares a constant whose value cannot be reassigned after it is set, while var declares a variable you can change later. Swift encourages let by default because immutable values are easier to reason about and let the compiler catch accidental changes. Use var only when the value genuinely needs to change.
- Does this cheat sheet send my searches anywhere?
- No. The entire snippet list is baked into the page and all filtering runs in your browser with JavaScript, so nothing you type leaves your device. Open your browser DevTools and watch the Network tab while you search to confirm there are zero requests.
Cite this tool
For academic, journalistic, or technical references. Pick a format:
Citations use 2026 as the publication year. Access date is left as a fillable placeholder where the citation style expects one.