Bird
Raised Fist0
iOS Swiftmobile~20 mins

Protocols in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Protocol Demo Screen
This screen shows how to use a protocol to make different shapes calculate their area. The user can tap buttons to see the area of a circle or a rectangle.
Target UI
-------------------------
| Protocol Demo Screen   |
|-----------------------|
| [Show Circle Area]     |
| [Show Rectangle Area]  |
|                       |
| Area:                 |
|                       |
-------------------------
Create a protocol named Shape with a method area() that returns Double.
Create two structs Circle and Rectangle that conform to Shape.
Circle has a radius property; Rectangle has width and height properties.
Add two buttons: 'Show Circle Area' and 'Show Rectangle Area'.
When a button is tapped, display the area of that shape below the buttons.
Starter Code
iOS Swift
import SwiftUI

struct ProtocolDemoScreen: View {
    @State private var areaText = ""

    var body: some View {
        VStack(spacing: 20) {
            Text("Protocol Demo Screen")
                .font(.title)

            Button("Show Circle Area") {
                // TODO: Calculate and show circle area
            }

            Button("Show Rectangle Area") {
                // TODO: Calculate and show rectangle area
            }

            Text("Area: \(areaText)")
                .font(.headline)
                .padding(.top, 40)

            Spacer()
        }
        .padding()
    }
}

// TODO: Define protocol Shape here

// TODO: Define struct Circle conforming to Shape

// TODO: Define struct Rectangle conforming to Shape

struct ProtocolDemoScreen_Previews: PreviewProvider {
    static var previews: some View {
        ProtocolDemoScreen()
    }
}
Task 1
Task 2
Task 3
Task 4
Solution
iOS Swift
import SwiftUI

protocol Shape {
    func area() -> Double
}

struct Circle: Shape {
    var radius: Double
    func area() -> Double {
        return Double.pi * radius * radius
    }
}

struct Rectangle: Shape {
    var width: Double
    var height: Double
    func area() -> Double {
        return width * height
    }
}

struct ProtocolDemoScreen: View {
    @State private var areaText = ""

    var body: some View {
        VStack(spacing: 20) {
            Text("Protocol Demo Screen")
                .font(.title)

            Button("Show Circle Area") {
                let circle = Circle(radius: 5)
                areaText = String(format: "%.2f", circle.area())
            }

            Button("Show Rectangle Area") {
                let rectangle = Rectangle(width: 4, height: 6)
                areaText = String(format: "%.2f", rectangle.area())
            }

            Text("Area: \(areaText)")
                .font(.headline)
                .padding(.top, 40)

            Spacer()
        }
        .padding()
    }
}

struct ProtocolDemoScreen_Previews: PreviewProvider {
    static var previews: some View {
        ProtocolDemoScreen()
    }
}

We created a protocol Shape with a method area() that returns a Double. Then we made two structs, Circle and Rectangle, that follow this protocol by implementing the area() method. The screen has two buttons. When you tap one, it creates the shape with fixed sizes and shows the area below. This shows how protocols let us write flexible code that works with different types in the same way.

Final Result
Completed Screen
-------------------------
| Protocol Demo Screen   |
|-----------------------|
| [Show Circle Area]     |
| [Show Rectangle Area]  |
|                       |
| Area: 78.54           |
|                       |
-------------------------
Tap 'Show Circle Area' button: area below updates to '78.54' (area of circle with radius 5).
Tap 'Show Rectangle Area' button: area below updates to '24.00' (area of rectangle 4x6).
Stretch Goal
Add a third shape, Triangle, that also conforms to Shape and calculate its area.
💡 Hint
Triangle area = 0.5 * base * height. Add a button to show triangle area.

Practice

(1/5)
1. What is the main purpose of a protocol in Swift?
easy
A. To create a new class with default behavior
B. To define a blueprint of methods and properties that a type must implement
C. To store data persistently on the device
D. To handle user interface layout automatically

Solution

  1. Step 1: Understand what a protocol defines

    A protocol specifies methods and properties that a type must implement, acting as a blueprint.
  2. Step 2: Differentiate from other concepts

    Protocols do not create classes or store data; they only define requirements.
  3. Final Answer:

    To define a blueprint of methods and properties that a type must implement -> Option B
  4. Quick Check:

    Protocol purpose = blueprint [OK]
Hint: Protocols define required methods and properties [OK]
Common Mistakes:
  • Confusing protocols with classes
  • Thinking protocols store data
  • Assuming protocols handle UI layout
2. Which of the following is the correct syntax to declare a protocol named Drivable in Swift?
easy
A. struct Drivable { func drive() }
B. class Drivable { func drive() }
C. func protocol Drivable() { drive() }
D. protocol Drivable { func drive() }

Solution

  1. Step 1: Identify correct protocol declaration syntax

    Protocols are declared with the keyword protocol followed by the name and curly braces.
  2. Step 2: Check method declaration inside protocol

    Methods inside protocols are declared without implementation, just the signature.
  3. Final Answer:

    protocol Drivable { func drive() } -> Option D
  4. Quick Check:

    Protocol syntax = keyword 'protocol' + name + method signatures [OK]
Hint: Use 'protocol' keyword, not class or struct [OK]
Common Mistakes:
  • Using class or struct instead of protocol
  • Adding method implementation inside protocol
  • Incorrect keyword order
3. Consider this Swift code:
protocol Greetable {
  func greet() -> String
}

struct Person: Greetable {
  func greet() -> String {
    return "Hello!"
  }
}

let p = Person()
print(p.greet())

What will be printed when this code runs?
medium
A. Hello!
B. greet()
C. Error: Missing protocol implementation
D. nil

Solution

  1. Step 1: Check protocol and struct conformance

    The struct Person adopts Greetable and implements the required greet() method returning "Hello!".
  2. Step 2: Understand the print statement output

    Calling p.greet() returns "Hello!", which is printed.
  3. Final Answer:

    Hello! -> Option A
  4. Quick Check:

    Implemented method returns "Hello!" [OK]
Hint: Implemented protocol methods run normally [OK]
Common Mistakes:
  • Expecting protocol name printed
  • Thinking missing implementation error occurs
  • Assuming nil is printed
4. What is wrong with this Swift code?
protocol Runnable {
  func run()
}

struct Athlete: Runnable {
  // Missing run() implementation
}
medium
A. No error, code is valid
B. Error: run() must have a return type
C. Error: Athlete does not implement required method run()
D. Error: Protocol Runnable cannot be adopted by struct

Solution

  1. Step 1: Check protocol requirements

    The protocol Runnable requires a method run() with no return value.
  2. Step 2: Verify struct conformance

    The struct Athlete adopts Runnable but does not implement run(), causing a compile error.
  3. Final Answer:

    Error: Athlete does not implement required method run() -> Option C
  4. Quick Check:

    Missing required method causes error [OK]
Hint: All protocol methods must be implemented [OK]
Common Mistakes:
  • Assuming structs can't adopt protocols
  • Thinking missing method is allowed
  • Expecting run() to require return type
5. You want to create a protocol Vehicle with a property speed that can be read and set. Which of these protocol declarations is correct?
hard
A. protocol Vehicle { var speed: Int { get set } }
B. protocol Vehicle { var speed: Int }
C. protocol Vehicle { func speed() -> Int }
D. protocol Vehicle { let speed: Int }

Solution

  1. Step 1: Understand property requirements in protocols

    To require a property to be readable and writable, use { get set } in the protocol.
  2. Step 2: Analyze each option

    protocol Vehicle { var speed: Int { get set } } correctly declares speed as a variable property with get set. protocol Vehicle { var speed: Int } misses get set, so it's read-only. protocol Vehicle { func speed() -> Int } declares a method, not a property. protocol Vehicle { let speed: Int } uses let, which is not allowed in protocols.
  3. Final Answer:

    protocol Vehicle { var speed: Int { get set } } -> Option A
  4. Quick Check:

    Writable property = var with get set [OK]
Hint: Use 'var' with { get set } for read-write properties [OK]
Common Mistakes:
  • Using 'let' in protocol properties
  • Omitting { get set } for writable properties
  • Confusing methods with properties
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard