READ IT. CHANGE IT. RUN IT.

Swift code examples

Every example includes an explanation and a link to open its source in the playground.

26 recipes

Dates

Compare two dates

Compare moments in time, or compare just the calendar day.

Read recipe →
Files

List directory contents

Read the immediate children of a directory.

Read recipe →
Files

Get the current directory

Find the working directory of the running process.

Read recipe →
Collections

Check whether a value is an array

Inspect an unknown value and access its elements safely.

Read recipe →
Collections

Remove duplicates from an array

Keep the first occurrence in the original order.

Read recipe →
JSON

Decode JSON into a Swift type

Replace untyped dictionaries with a Decodable model.

Read recipe →
JSON

Encode a model as JSON

Serialize a model with stable, readable formatting.

Read recipe →
Collections

Sort an array of records

Sort by a property without changing the original array.

Read recipe →
Basics

Unwrap an optional safely

Handle a missing value without force-unwrapping.

Read recipe →
Dates

Format a date

Use an explicit locale and time zone for a fixed format.

Read recipe →
Dates

Parse an ISO 8601 date

Turn an internet timestamp into a Date.

Read recipe →
Dates

Add calendar days to a date

Account for calendar and daylight-saving changes.

Read recipe →
Collections

Filter an array

Select values that satisfy a condition.

Read recipe →
Collections

Transform an array

Transform every element, or discard nil results.

Read recipe →
Collections

Group values by a key

Create a dictionary of arrays from a collection.

Read recipe →
Collections

Merge dictionaries

Choose which value wins when keys collide.

Read recipe →
Strings

Split a string

Split text into fields and trim whitespace.

Read recipe →
Strings

Find a substring

Check case-sensitive or case-insensitive matches.

Read recipe →
Strings

Replace a substring

Replace occurrences without changing the original value.

Read recipe →
Files

Read a UTF-8 text file

Read a file and handle filesystem errors.

Read recipe →
Files

Write a UTF-8 text file

Save text using an atomic replacement.

Read recipe →
Basics

Model choices with an enum

Name a finite set of states and switch over them.

Read recipe →
Basics

Throw and handle an error

Represent a recoverable failure explicitly.

Read recipe →
Concurrency

Call an asynchronous function

Await a result at a possible suspension point.

Read recipe →
Concurrency

Protect shared state with an actor

Isolate mutable state behind actor methods.

Read recipe →
Networking

Fetch JSON with URLSession

Validate HTTP status before decoding the response.

Read recipe →