0
0
iOS Swiftmobile~20 mins

Protocols in iOS Swift - Mini App: Build & Ship

Choose your learning style9 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.