The Swift Cookbook
Find the pattern you need, understand how it works, and try it in the playground.
26 recipes
Compare two dates
Compare moments in time, or compare just the calendar day.
Read recipe →FilesList directory contents
Read the immediate children of a directory.
Read recipe →FilesGet the current directory
Find the working directory of the running process.
Read recipe →CollectionsCheck whether a value is an array
Inspect an unknown value and access its elements safely.
Read recipe →CollectionsRemove duplicates from an array
Keep the first occurrence in the original order.
Read recipe →JSONDecode JSON into a Swift type
Replace untyped dictionaries with a Decodable model.
Read recipe →JSONEncode a model as JSON
Serialize a model with stable, readable formatting.
Read recipe →CollectionsSort an array of records
Sort by a property without changing the original array.
Read recipe →BasicsUnwrap an optional safely
Handle a missing value without force-unwrapping.
Read recipe →DatesFormat a date
Use an explicit locale and time zone for a fixed format.
Read recipe →DatesParse an ISO 8601 date
Turn an internet timestamp into a Date.
Read recipe →DatesAdd calendar days to a date
Account for calendar and daylight-saving changes.
Read recipe →CollectionsFilter an array
Select values that satisfy a condition.
Read recipe →CollectionsTransform an array
Transform every element, or discard nil results.
Read recipe →CollectionsGroup values by a key
Create a dictionary of arrays from a collection.
Read recipe →CollectionsMerge dictionaries
Choose which value wins when keys collide.
Read recipe →StringsSplit a string
Split text into fields and trim whitespace.
Read recipe →StringsFind a substring
Check case-sensitive or case-insensitive matches.
Read recipe →StringsReplace a substring
Replace occurrences without changing the original value.
Read recipe →FilesRead a UTF-8 text file
Read a file and handle filesystem errors.
Read recipe →FilesWrite a UTF-8 text file
Save text using an atomic replacement.
Read recipe →BasicsModel choices with an enum
Name a finite set of states and switch over them.
Read recipe →BasicsThrow and handle an error
Represent a recoverable failure explicitly.
Read recipe →ConcurrencyCall an asynchronous function
Await a result at a possible suspension point.
Read recipe →ConcurrencyProtect shared state with an actor
Isolate mutable state behind actor methods.
Read recipe →NetworkingFetch JSON with URLSession
Validate HTTP status before decoding the response.
Read recipe →