Bird
Raised Fist0
Swiftprogramming~20 mins

Protocol as types in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Protocol Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Swift code using protocol as type?
Consider the following Swift code where a protocol is used as a type. What will be printed when the code runs?
Swift
protocol Vehicle {
    func description() -> String
}

struct Car: Vehicle {
    func description() -> String {
        return "Car"
    }
}

struct Bike: Vehicle {
    func description() -> String {
        return "Bike"
    }
}

func printVehicle(_ v: Vehicle) {
    print(v.description())
}

let myVehicle: Vehicle = Car()
printVehicle(myVehicle)
ACar
BBike
CVehicle
DCompilation error
Attempts:
2 left
💡 Hint
Remember that the variable is declared as the protocol type but holds a Car instance.
❓ Predict Output
intermediate
2:00remaining
What error occurs when assigning a non-conforming type to a protocol variable?
Given the protocol and struct below, what happens if you try to assign a String to a variable of type Vehicle?
Swift
protocol Vehicle {
    func description() -> String
}

struct Car: Vehicle {
    func description() -> String {
        return "Car"
    }
}

let myVehicle: Vehicle = "Not a vehicle"
ANo error, but description() returns empty string
BRuntime error: Cannot cast String to Vehicle
CThe code compiles and prints "Not a vehicle"
DCompilation error: String does not conform to Vehicle
Attempts:
2 left
💡 Hint
Check if String implements the Vehicle protocol.
🔧 Debug
advanced
2:30remaining
Why does this code cause a runtime error when using protocol as type?
Examine the code below. It compiles but crashes at runtime. What is the cause?
Swift
protocol Vehicle {
    func description() -> String
}

struct Car: Vehicle {
    func description() -> String {
        return "Car"
    }
}

struct Bike: Vehicle {
    func description() -> String {
        return "Bike"
    }
}

let myVehicle: Vehicle = Car()
let bike = myVehicle as! Bike
print(bike.description())
ACompilation error: Bike not defined
BRuntime crash due to forced cast from Car to Bike failing
CPrints "Car" without error
DRuntime crash due to missing description() method
Attempts:
2 left
💡 Hint
Check the forced cast from one type to another unrelated type.
🧠 Conceptual
advanced
2:00remaining
How does Swift use protocols as types to enable polymorphism?
Which statement best explains how using a protocol as a type enables polymorphism in Swift?
AA protocol type variable can hold any instance of a type that conforms to that protocol, allowing different implementations to be used interchangeably.
BProtocols store the actual data of conforming types, so variables of protocol type contain all properties directly.
CUsing a protocol as a type disables dynamic dispatch and forces static method calls.
DProtocols can only be used as types if they have no methods or properties.
Attempts:
2 left
💡 Hint
Think about how different types can be treated the same way through a protocol.
📝 Syntax
expert
2:30remaining
Which option correctly declares a variable of protocol type with an instance conforming to it?
Given the protocol and struct below, which option correctly declares a variable of type Vehicle and assigns a Car instance?
Swift
protocol Vehicle {
    func description() -> String
}

struct Car: Vehicle {
    func description() -> String {
        return "Car"
    }
}
Alet myVehicle: Car = Vehicle()
Blet myVehicle = Vehicle(Car())
Clet myVehicle: Vehicle = Car()
Dlet myVehicle: Vehicle = Vehicle()
Attempts:
2 left
💡 Hint
Remember protocols cannot be instantiated directly.

Practice

(1/5)
1. What does it mean to use a protocol as a type in Swift?
easy
A. Any object that follows the protocol's rules can be used as that type.
B. Only classes can conform to the protocol.
C. Protocols can only be used to create new classes.
D. Protocols define stored properties for types.

Solution

  1. Step 1: Understand what a protocol defines

    A protocol defines a set of rules or features that a type must implement.
  2. Step 2: Using protocol as a type

    When a protocol is used as a type, any object that implements those rules can be assigned to that type.
  3. Final Answer:

    Any object that follows the protocol's rules can be used as that type. -> Option A
  4. Quick Check:

    Protocol as type means flexible object use = A [OK]
Hint: Protocol as type means any conforming object fits [OK]
Common Mistakes:
  • Thinking protocols only apply to classes
  • Believing protocols define stored properties
  • Confusing protocol usage with inheritance
2. Which of the following is the correct way to declare a variable of a protocol type named Drawable?
easy
A. var shape: Drawable
B. var shape: Drawable()
C. var shape: Drawable = Drawable()
D. var shape: Drawable[]

Solution

  1. Step 1: Understand protocol type declaration

    To declare a variable of a protocol type, use the protocol name without parentheses or brackets.
  2. Step 2: Analyze options

    var shape: Drawable correctly declares a variable of type Drawable. Options A and B incorrectly try to instantiate a protocol, which is not allowed. var shape: Drawable[] uses invalid syntax.
  3. Final Answer:

    var shape: Drawable -> Option A
  4. Quick Check:

    Protocol type variable = var name: ProtocolName [OK]
Hint: Declare protocol type without parentheses or initialization [OK]
Common Mistakes:
  • Trying to instantiate a protocol directly
  • Using parentheses after protocol name
  • Using array brackets incorrectly
3. What will be the output of this Swift code?
protocol Greetable {
    func greet() -> String
}

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

let greeter: Greetable = Person()
print(greeter.greet())
medium
A. greet()
B. Compile error
C. Person
D. Hello

Solution

  1. Step 1: Understand protocol conformance

    Person struct conforms to Greetable and implements greet() returning "Hello".
  2. Step 2: Using protocol as type and calling method

    Variable greeter is of type Greetable but holds a Person instance, so calling greet() returns "Hello".
  3. Final Answer:

    Hello -> Option D
  4. Quick Check:

    Protocol method call returns implemented string = Hello [OK]
Hint: Protocol variable calls conforming type's method [OK]
Common Mistakes:
  • Expecting protocol name or method name as output
  • Thinking protocol cannot be used as variable type
  • Confusing compile error with runtime behavior
4. Identify the error in this Swift code using protocol as a type:
protocol Vehicle {
    func start()
}

class Car: Vehicle {
    func start() {
        print("Car started")
    }
}

var myVehicle: Vehicle = Vehicle()
myVehicle.start()
medium
A. Variable myVehicle should be a class, not protocol
B. Missing method implementation in Car
C. Cannot instantiate protocol directly with Vehicle()
D. start() method should return a value

Solution

  1. Step 1: Check protocol instantiation

    Protocols cannot be instantiated directly, so Vehicle() causes an error.
  2. Step 2: Analyze variable assignment

    Variable myVehicle must hold an instance of a type conforming to Vehicle, like Car(), not Vehicle() itself.
  3. Final Answer:

    Cannot instantiate protocol directly with Vehicle() -> Option C
  4. Quick Check:

    Protocols can't be created with () = Error [OK]
Hint: Protocols can't be instantiated directly [OK]
Common Mistakes:
  • Trying to create an instance of a protocol
  • Confusing protocol with class instantiation
  • Ignoring method return types
5. Given the protocol and classes below, which code correctly stores different types conforming to Animal in an array and calls sound() on each?
protocol Animal {
    func sound() -> String
}

class Dog: Animal {
    func sound() -> String { "Bark" }
}

class Cat: Animal {
    func sound() -> String { "Meow" }
}
hard
A. let animals: [Animal] = [Dog(), Cat()] for animal in animals { print(animal.sound) }
B. let animals: [Animal] = [Dog(), Cat()] for animal in animals { print(animal.sound()) }
C. let animals: [Dog] = [Dog(), Cat()] for animal in animals { print(animal.sound()) }
D. let animals = [Dog(), Cat()] for animal in animals { print(animal.sound()) }

Solution

  1. Step 1: Understand protocol array usage

    To store different types conforming to Animal, declare array as [Animal].
  2. Step 2: Call method correctly

    Use animal.sound() with parentheses to call the method. let animals: [Animal] = [Dog(), Cat()] for animal in animals { print(animal.sound()) } does this correctly.
  3. Final Answer:

    let animals: [Animal] = [Dog(), Cat()] for animal in animals { print(animal.sound()) } -> Option B
  4. Quick Check:

    Protocol array with method calls = let animals: [Animal] = [Dog(), Cat()] for animal in animals { print(animal.sound()) } [OK]
Hint: Use protocol array type and call methods with () [OK]
Common Mistakes:
  • Using concrete type array instead of protocol type
  • Calling method without parentheses
  • Mixing incompatible types in array
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