Swift code snippets with use cases
30 ready-made code building blocks, sorted by topic.
Control flow
- if / else if / else – Reacting differently, e.g. calculating grades or price tiers.
- for-in loop – Processing every element of a list or repeating n times.
- guard for early exits – Validating input and then continuing flat, instead of nesting deeply.
Data structures
- Working with an array – Managing collections of values: adding, sorting, filtering.
- Dictionary – Storing mappings, e.g. configurations or counters.
- Sorting by a criterion – Ordering records by a field, e.g. users by age or name.
OOP
- Class with inheritance – Bundling data and behavior, e.g. users, products, game characters.
- Struct copies, class shares – Understanding why changes sometimes affect the copy and sometimes the original (models…
- Enum with associated values – Modeling states or results (loading state, commands, network response), with the…
Error handling
- do / try / catch / defer – Guarding user input or file access without crashing the program.
- Optional binding and ?? – Safely using values that may be missing (input, search results) instead of crashing.
- The Result type – Passing success or failure along as a value (callbacks, validation, tests).
Strings
- Manipulating text – Cleaning, splitting, and checking user input (search, forms, log lines).
- Counting words – Text analysis, e.g. the most frequent words in a document.
- Regular expression – Finding email addresses, phone numbers, or patterns in text.
Concurrency
- Using async/await – Writing network or database calls without callback nesting.
- Running tasks in parallel with TaskGroup – Running many independent tasks at the same time (downloads, image computations) and…
- Actor for safe state – Keeping shared mutable state (counters, caches) thread-safe without locks.
More snippets
- Hello World – A first test of whether Swift and the environment work.
- Variables and types – Storing values and checking their type; separating constants from mutable values.
- Function with a default value – Bundling recurring logic, e.g. greeting texts or calculations.
- map, filter, reduce – Processing data: converting, selecting, aggregating (prices, measurements, lists).
- Reading and writing a file – Saving and loading logs, configurations, or text data.
- JSON with Codable – Exchanging data with web APIs or files without parsing by hand.
- Protocol with a default implementation – Defining shared behavior for many types without inheritance (plugins, shapes, data…
- Extension for existing types – Attaching helper functions directly to standard types (e.g. string helpers in a project).
- SwiftUI counter – Building a reactive interface: change the state, and the view updates itself.
- HTTP request with URLSession – Fetching data from a web API and decoding it.
- weak self in closures – Avoiding memory leaks caused by callbacks and timers in classes.
- Writing a unit test – Checking functions automatically so that changes do not break anything.