Skip to content
Justice Tech School

Swift Exercises

Fill in the blanks to check your knowledge. Each exercise belongs to a lesson.

Swift Introduction

Exercise

Print a line.

("Hi")

Swift Get Started

Exercise

File extension.

hello.

Swift Syntax

Exercise

Single line comment.

 note

Swift Variables and Constants

Exercise

Make a constant.

 max = 10

Swift Data Types

Exercise

Convert Int to Double.

let x = (i)

Swift Strings

Exercise

Count characters.

s.

Swift Optionals

Exercise

Default value.

name  "none"

Swift Type Conversion

Exercise

Number to text.

(42)

Swift Tuples

Exercise

Group values.

let t = (1 "a")

Swift Booleans

Exercise

Flip a Bool.

on.()

Type Safety and Aliases

Exercise

Name an existing type.

 Id = Int

Swift Comments

Exercise

Start a line comment.

 note

Swift Numbers and Math

Exercise

Largest of two.

(3, 9)

let and var

Exercise

Constant keyword.

 pi = 3.14

Basic Types

Exercise

Convert to Double.

(i)

Optionals

Exercise

Default value.

x  "none"

String Interpolation

Exercise

Insert a value.

"Hi (n)"

Tuples

Exercise

Read by name.

p.

Operators

Exercise

Half open range.

13

Type Casting

Exercise

Safe cast.

x ? Int

Math and Random

Exercise

Random in a range.

Int.random(in: )

Reading Input

Exercise

Read a line.

()

Type Aliases and Constants

Exercise

Alias keyword.

 ID = Int

print Options

Exercise

Change the separator.

print("a", "b", : "-")

Comments

Exercise

Doc comment.

 Adds two numbers

Number Literals and Overflow

Exercise

Hex prefix.

let h = FF

Identity and Equality

Exercise

Same instance.

a  b

Optional Binding Patterns

Exercise

Short binding.

if let  { }

assert and precondition

Exercise

Always checked.

(cond, "msg")

Swift Operators

Exercise

Remainder operator.

17  5

Swift Ranges

Exercise

Stop before the end.

14

Swift If and Else

Exercise

Second branch.

if a {}  if b {}

Swift Switch

Exercise

Fallback case.

switch x { : break }

Swift Loops

Exercise

Run at least once.

 { } while x

Swift Guard

Exercise

Exit early keyword.

 let x = y else { return }

if and else

Exercise

Else branch.

if x {}  {}

switch

Exercise

Default case.

: print("x")

for in Loops

Exercise

Index and value.

for (i, v) in a.()

while and repeat

Exercise

Run once at least.

 { } while c

guard

Exercise

Early exit.

 cond else { return }

break, continue and Labels

Exercise

Skip a round.

Ranges

Exercise

Half open.

03

Swift Arrays

Exercise

Add an item.

list.("x")

Swift Dictionaries

Exercise

Missing key result.

ages["x"] is 

map, filter and reduce

Exercise

Transform every item.

n. { $0 * 2 }

Swift Sets

Exercise

Combine two sets.

a.(b)

Sorting and Searching

Exercise

Sort in place.

n.()

Arrays

Exercise

Add an item.

a.(5)

Array Operations

Exercise

Sum.

n.(0, +)

Sets

Exercise

Common items.

a.(b)

Dictionaries

Exercise

Default for missing.

d["x"]  0

Slices and Ranges

Exercise

Copy a slice.

(slice)

Grouping and Zipping

Exercise

Pair arrays.

(a, b)

compactMap and flatMap

Exercise

Drop nils.

s. { Int($0) }

Strings

Exercise

Prefix test.

s.("He")

String Indexing

Exercise

Move an index.

s.index(s.startIndex, : 2)

Swift Functions

Exercise

Return type arrow.

func f()  Int { 1 }

Swift Closures

Exercise

Closure separator.

{ x  x * 2 }

Variadic and inout Parameters

Exercise

Pass by reference marker.

double(v)

Functions

Exercise

Return arrow.

func f()  Int

Default and Variadic Parameters

Exercise

Variadic.

_ n: Int

inout Parameters

Exercise

Pass by reference.

double(x)

Closures

Exercise

Shorthand argument.

n.map {  * 2 }

Functions as Values

Exercise

Function type.

(Int)  Int

Recursion

Exercise

Base case.

if n <=  { return 1 }

Nested Functions and Scope

Exercise

Inner function.

func outer() {  inner() {} }

Swift Structs

Exercise

Method that changes a struct.

 func move() {}

Swift Classes

Exercise

Initializer name.

(name: String) {}

Swift Properties

Exercise

Run after a change.

var x = 0 {  { } }

Swift Inheritance

Exercise

Replace a method.

 func speak()

Swift Protocols

Exercise

Declare a protocol.

 Shape { }

Swift Extensions

Exercise

Add to an existing type.

 String { }

Swift Enums

Exercise

Declare an enum.

 Color { case red }

Access Control

Exercise

Hide from outside.

 var secret = 1

Structs

Exercise

Value type keyword.

 Point {}

Classes

Exercise

Initialiser.

(name: String)

Properties

Exercise

Calculated property.

var area: Double  w * h

Methods and mutating

Exercise

Change self.

 func inc()

Inheritance

Exercise

Replace a method.

 func sound()

Protocols

Exercise

Adopt a protocol.

struct A:  {}

Extensions

Exercise

Extend a type.

 Int { }

Enums

Exercise

Associated value.

case ok()

Generics

Exercise

Type parameter.

func f<>(x: T) {}

Optional Chaining

Exercise

Chain safely.

user.address.city

Access Control

Exercise

Hide a setter.

private() var x

Initialisers

Exercise

Failable init.

init(k: Double)

Swift Error Handling

Exercise

Mark a function that can fail.

func f()  {}

Memory and ARC

Exercise

Avoid retain cycles.

 var owner: Owner?

Errors with throw and do catch

Exercise

Mark a throwing function.

func f()  {}

try? and try!

Exercise

Turn errors into nil.

? parse("x")

defer

Exercise

Run at scope end.

 { cleanup() }

Memory and ARC

Exercise

Avoid cycles.

 var next: Node?

Result Type

Exercise

Success case.

.(42)

Codable and JSON

Exercise

Adopt Codable.

struct P:  {}

Dates and Files

Exercise

Format a date.

DateFormatter().

async and await

Exercise

Wait for async.

 load()

Practice: Word Frequency

Exercise

Default for missing key.

freq[w, : 0] += 1

Practice: FizzBuzz

Exercise

Tuple pattern.

case (0, ):

Practice: Bank Account

Exercise

Validate first.

 n > 0 else { throw E }

Swift Generics

Premium exercise. See plans

Swift Concurrency

Premium exercise. See plans

Property Wrappers and Result Builders

Premium exercise. See plans

Opaque Types and some

Premium exercise. See plans

Codable and JSON

Premium exercise. See plans

SwiftUI Basics

Premium exercise. See plans

SwiftUI State and Binding

Premium exercise. See plans

SwiftUI Lists and Navigation

Premium exercise. See plans

Networking with URLSession

Premium exercise. See plans

Saving Data

Premium exercise. See plans

Testing Swift

Premium exercise. See plans

Swift Package Manager

Premium exercise. See plans

Publishing to the App Store

Premium exercise. See plans

Swift Best Practices

Premium exercise. See plans