Thuta Learning
Swift
ExercisesProgrammingBeginner

Exercise Set 2: Struct, Protocol & Error Handling Practice

SwiftLesson 3440 min

What you'll walk away with

  • Explain the type, ownership, and runtime behavior of Exercise Set 2: Struct, Protocol & Error Handling Practice
  • Test nil, error, boundary, and concurrency cases
  • Write safe and testable Swift

Explain it simply

Exercise Set 2: Struct, Protocol & Error Handling Practice, in plain language

This exercise set is harder than Exercise Set 1, and it's meant to combine practice on the protocol, closure, enum with associated value, and error handling topics from the Intermediate/Advanced chapter. It's not new teaching content — it's a self-test where you apply the concepts by writing code yourself. The tasks are independent of the Task Manager project, designed so you can practice each concept in isolation. After solving each one, read any compile errors yourself and try to fix them.

Problem → Why → Solution

The problem — why this concept matters

Declaring a protocol requirement as { get } but implementing it as a stored property instead of adding any computed property logic

A common mistake

When catching an error from a throws function, using a single general catch { } instead of switch-style pattern matching (catch InvalidAgeError.outOfRange), losing the error detail

Core concept — understand how it works

Build Exercise Set 2: Struct, Protocol & Error Handling Practice in vertical slices that separate UI, domain state, persistence or services, and tests. Cover normal, boundary, nil, error, cancellation, and concurrency paths without blocking main-actor work.

Mental model
  1. requirement
  2. reason and implement
  3. test and explain

Explain the type, ownership, and runtime behavior of Exercise Set 2: Struct, Protocol & Error Handling Practice

Core syntax or pattern

swift
// Task 1
protocol Shape {
    var area: Double { get }
}

struct Circle: Shape {
    let radius: Double
    var area: Double {
        // TODO: implement
        return 0
    }
}

struct Rectangle: Shape {
    let width: Double
    let height: Double
    var area: Double {
        // TODO: implement
        return 0
    }
}

// Task 2
let circles = [Circle(radius: 3), Circle(radius: 1), Circle(radius: 2)]
// TODO: sorted(by:) closure

// Task 3
enum NetworkResult {
    case success(data: String)
    case failure(reason: String)
}
// TODO: switch statement

// Task 4
enum InvalidAgeError: Error {
    case outOfRange
}
func validateAge(_ age: Int) throws -> Int {
    // TODO: implement
    return age
}

Build Exercise Set 2: Struct, Protocol & Error Handling Practice in vertical slices that separate UI, domain state, persistence or services, and tests. Cover normal, boundary, nil, error, cancellation, and concurrency paths without blocking main-actor work.

Read the code step by step

  1. requirement// Task 1

    This exercise set is harder than Exercise Set 1, and it's meant to combine practice on the protocol, closure, enum with associated value, and error handling topics from the Intermediate/Advanced chapter. It's not new teaching content — it's a self-test where you apply the concepts by writing code yourself. The tasks are independent of the Task Manager project, designed so you can practice each concept in isolation. After solving each one, read any compile errors yourself and try to fix them.

  2. reason and implement}

    Build Exercise Set 2: Struct, Protocol & Error Handling Practice in vertical slices that separate UI, domain state, persistence or services, and tests. Cover normal, boundary, nil, error, cancellation, and concurrency paths without blocking main-actor work.

  3. test and explain}

    Run and test an original Exercise Set 2: Struct, Protocol & Error Handling Practice example with empty, nil, boundary, invalid, error, and cancellation cases. Verify value copying, shared references, actor isolation, and main-actor effects where relevant.

Execution flow
  1. requirement
  2. reason and implement
  3. test and explain

Success

Explain the type, ownership, and runtime behavior of Exercise Set 2: Struct, Protocol & Error Handling Practice

Failure

Declaring a protocol requirement as { get } but implementing it as a stored property instead of adding any computed property logic

Let's think about this for a second

This exercise set is harder than Exercise Set 1, and it's meant to combine practice on the protocol, closure, enum with associated value, and error handling topics from the Intermediate/Advanced chapter. It's not new teaching content — it's a self-test where you apply the concepts by writing code yourself. The tasks are independent of the Task Manager project, designed so you can practice each concept in isolation. After solving each one, read any compile errors yourself and try to fix them.

Exercises

Task 1: Build a Shape protocol with a var area: Double { get } requirement and make Circle and Rectangle structs conform to it. Task 2: Build a [Circle] array and use closure-based sorted(by:) to sort it from smallest to largest area. Task 3: Build a NetworkResult enum with two associated values, success(data: String) and failure(reason: String), and handle both cases with a switch statement. Task 4: Write a validateAge(_ age: Int) throws -> Int function that throws a custom Error enum (InvalidAgeError) if age is below 0 or above 120, and handle it with do-catch.

Sample Code

swift
// Task 1
protocol Shape {
    var area: Double { get }
}

struct Circle: Shape {
    let radius: Double
    var area: Double {
        // TODO: implement
        return 0
    }
}

struct Rectangle: Shape {
    let width: Double
    let height: Double
    var area: Double {
        // TODO: implement
        return 0
    }
}

// Task 2
let circles = [Circle(radius: 3), Circle(radius: 1), Circle(radius: 2)]
// TODO: sorted(by:) closure

// Task 3
enum NetworkResult {
    case success(data: String)
    case failure(reason: String)
}
// TODO: switch statement

// Task 4
enum InvalidAgeError: Error {
    case outOfRange
}
func validateAge(_ age: Int) throws -> Int {
    // TODO: implement
    return age
}
You should see
The Circle/Rectangle area calculations should be correct, the circles array should be sorted by radius order (1, 2, 3), and calling validateAge(150) should have the catch block correctly catch the InvalidAgeError.outOfRange error.

Give it 5 minutes

Add a loading case to the NetworkResult enum from Task 3 and update the switch statement to stay exhaustive. Try it yourself for about 5 minutes.

One thing to watch out for

When switching over an enum with associated values, you need to cover every case — reaching for a default case too easily means the compiler won't warn you when a new case gets added later, and you can end up with a silent logic bug.

Real-world usage

How to apply it in a real project

Run and test an original Exercise Set 2: Struct, Protocol & Error Handling Practice example with empty, nil, boundary, invalid, error, and cancellation cases. Verify value copying, shared references, actor isolation, and main-actor effects where relevant.

Mini challenge

Build it yourself

Run and test an original Exercise Set 2: Struct, Protocol & Error Handling Practice example with empty, nil, boundary, invalid, error, and cancellation cases. Verify value copying, shared references, actor isolation, and main-actor effects where relevant.

  • Rebuild the example without copying it
  • Test a normal input and an edge case
  • Predict the compiler or output result before running it
swift
// Task 1
protocol Shape {
    var area: Double { get }
}

struct Circle: Shape {
    let radius: Double
    var area: Double {
        // TODO: implement
        return 0
    }
}

struct Rectangle: Shape {
    let width: Double
    let height: Double
    var area: Double {
        // TODO: implement
        return 0
    }
}

// Task 2
let circles = [Circle(radius: 3), Circle(radius: 1), Circle(radius: 2)]
// TODO: sorted(by:) closure

// Task 3
enum NetworkResult {
    case success(data: String)
    case failure(reason: String)
}
// TODO: switch statement

// Task 4
enum InvalidAgeError: Error {
    case outOfRange
}
func validateAge(_ age: Int) throws -> Int {
    // TODO: implement
    return age
}

Expected: Explain the type, ownership, and runtime behavior of Exercise Set 2: Struct, Protocol & Error Handling Practice

Show hint

Run and test an original Exercise Set 2: Struct, Protocol & Error Handling Practice example with empty, nil, boundary, invalid, error, and cancellation cases. Verify value copying, shared references, actor isolation, and main-actor effects where relevant.

Quick quiz 1 / 3

What best describes the core idea of Exercise Set 2: Struct, Protocol & Error Handling Practice?

Quick quiz 2 / 3

Which mistake should you avoid first?

Quick quiz 3 / 3

How should this be applied in a real project?

What to remember

  • requirement → reason and implement → test and explain
  • Build Exercise Set 2: Struct, Protocol & Error Handling Practice in vertical slices that separate UI, domain state, persistence or services, and tests. Cover normal, boundary, nil, error, cancellation, and concurrency paths without blocking main-actor work.
  • Declaring a protocol requirement as { get } but implementing it as a stored property instead of adding any computed property logic
  • Run and test an original Exercise Set 2: Struct, Protocol & Error Handling Practice example with empty, nil, boundary, invalid, error, and cancellation cases. Verify value copying, shared references, actor isolation, and main-actor effects where relevant.

The Swift Programming Language — Swift.org

Easy traps

  • Declaring a protocol requirement as { get } but implementing it as a stored property instead of adding any computed property logic
  • When catching an error from a throws function, using a single general catch { } instead of switch-style pattern matching (catch InvalidAgeError.outOfRange), losing the error detail
  • Assuming one sample output proves nil, ownership, actor isolation, and every error path.

Hands-on Exercise

Run and test an original Exercise Set 2: Struct, Protocol & Error Handling Practice example with empty, nil, boundary, invalid, error, and cancellation cases. Verify value copying, shared references, actor isolation, and main-actor effects where relevant.

You'll know it worked when: The Circle/Rectangle area calculations should be correct, the circles array should be sorted by radius order (1, 2, 3), and calling validateAge(150) should have the catch block correctly catch the InvalidAgeError.outOfRange error.

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Exercise Set 2: Struct, Protocol & Error Handling Practice | Thuta Learning