Bird
Raised Fist0
Swiftprogramming~20 mins

Type constraints with protocol conformance in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Protocol Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of generic function with protocol constraint

What is the output of this Swift code?

Swift
protocol Describable {
    func describe() -> String
}

struct Person: Describable {
    var name: String
    func describe() -> String {
        return "Person named \(name)"
    }
}

func printDescription<T: Describable>(_ item: T) {
    print(item.describe())
}

let p = Person(name: "Alice")
printDescription(p)
ANo output
BPerson named p
CError: Type 'Person' does not conform to protocol 'Describable'
DPerson named Alice
Attempts:
2 left
💡 Hint

Check how the describe() method is implemented and called.

🧠 Conceptual
intermediate
1:30remaining
Understanding protocol conformance in type constraints

Which statement about Swift type constraints with protocol conformance is true?

AA generic type constrained to a protocol can only accept types that implement all protocol requirements.
BProtocols cannot be used as constraints in generic functions.
CA generic type constrained to a protocol can accept any type, regardless of conformance.
DType constraints with protocols allow only classes, not structs or enums.
Attempts:
2 left
💡 Hint

Think about what it means to constrain a generic type to a protocol.

🔧 Debug
advanced
2:00remaining
Identify the error in protocol conformance with type constraints

What error does this Swift code produce?

Swift
protocol Runnable {
    func run()
}

struct Car: Runnable {
    func run() {
        print("Car is running")
    }
}

func start<T: Runnable>(_ vehicle: T) {
    vehicle.run()
}

struct Bike {}

start(Bike())
ARuntime error: method 'run()' not found
BError: Missing implementation of 'run()' in 'Bike'
CError: Type 'Bike' does not conform to protocol 'Runnable'
DNo error, prints 'Car is running'
Attempts:
2 left
💡 Hint

Check the type passed to the generic function and its protocol conformance.

📝 Syntax
advanced
1:30remaining
Correct syntax for protocol conformance in generic constraints

Which option shows the correct syntax to constrain a generic type T to conform to protocol Equatable?

Afunc compare<T: Equatable>(a: T, b: T) -> Bool { return a == b }
Bfunc compare<T where T: Equatable>(a: T, b: T) -> Bool { return a == b }
Cfunc compare<T: Equatable where T == Equatable>(a: T, b: T) -> Bool { return a == b }
Dfunc compare<T: Equatable>(a: T, b: T) -> Bool { return a.equals(b) }
Attempts:
2 left
💡 Hint

Recall the syntax for generic constraints in Swift function declarations.

🚀 Application
expert
2:30remaining
Determine the number of items in the filtered array

Given the following Swift code, how many items are in the filtered array after execution?

Swift
protocol Filterable {
    var isActive: Bool { get }
}

struct Item: Filterable {
    var isActive: Bool
}

func filterActive<T: Filterable>(_ items: [T]) -> [T] {
    items.filter { $0.isActive }
}

let items = [Item(isActive: true), Item(isActive: false), Item(isActive: true), Item(isActive: false)]
let filtered = filterActive(items)
print(filtered.count)
A4
B2
C0
D3
Attempts:
2 left
💡 Hint

Count how many Item instances have isActive set to true.

Practice

(1/5)
1. What does the syntax <T: ProtocolName> mean in Swift?
easy
A. It means type T must conform to ProtocolName.
B. It means type T inherits from ProtocolName.
C. It means ProtocolName is a subclass of T.
D. It means T is an instance of ProtocolName.

Solution

  1. Step 1: Understand generic type constraints

    The syntax <T: ProtocolName> restricts T to types that conform to ProtocolName.
  2. Step 2: Differentiate from inheritance and instances

    Protocols define requirements, not inheritance. T must implement ProtocolName, not inherit or be an instance.
  3. Final Answer:

    It means type T must conform to ProtocolName. -> Option A
  4. Quick Check:

    Type constraint = must conform [OK]
Hint: Remember: means T follows that protocol [OK]
Common Mistakes:
  • Confusing protocol conformance with class inheritance
  • Thinking T is an instance, not a type
  • Mixing subclass and protocol concepts
2. Which of the following is the correct syntax to declare a generic function with a type constrained to the Equatable protocol?
easy
A. func compare(a: T, b: T) -> Bool {}
B. func compare(a: T, b: T) -> Bool {}
C. func compare(a: T, b: T) -> Bool {}
D. func compare<T>(a: T, b: T) -> Bool where T Equatable {}

Solution

  1. Step 1: Recall correct generic constraint syntax

    The correct syntax uses <T: Equatable> to constrain T to Equatable.
  2. Step 2: Identify syntax errors in other options

    A uses 'where' incorrectly inside angle brackets, B misses colon after T, D misplaces 'where' and lacks colon.
  3. Final Answer:

    func compare<T: Equatable>(a: T, b: T) - correct syntax -> Option A
  4. Quick Check:

    Use colon after T for protocol constraint [OK]
Hint: Use colon after T to add protocol constraint [OK]
Common Mistakes:
  • Omitting colon ':' after generic type
  • Misplacing 'where' clause
  • Incorrect angle bracket usage
3. What will be the output of this Swift code?
protocol Printable {
    func printValue()
}

struct Number: Printable {
    var value: Int
    func printValue() {
        print("Value is \(value)")
    }
}

func show(_ item: T) {
    item.printValue()
}

let num = Number(value: 10)
show(num)
medium
A. Compile error: Missing protocol conformance
B. Value is num
C. Value is 10
D. Runtime error

Solution

  1. Step 1: Check protocol conformance

    Number struct conforms to Printable and implements printValue() correctly.
  2. Step 2: Analyze function call

    show() accepts any Printable type; passing Number instance calls printValue(), printing "Value is 10".
  3. Final Answer:

    Value is 10 -> Option C
  4. Quick Check:

    Protocol method called prints value [OK]
Hint: Check if type implements protocol method before calling [OK]
Common Mistakes:
  • Assuming protocol methods are optional
  • Forgetting to implement protocol methods
  • Confusing print output with variable name
4. Identify the error in this Swift code snippet:
protocol Describable {
    func describe() -> String
}

func printDescription<T>(item: T) where T: Describable {
    print(item.describe())
}

struct Person {
    var name: String
}

let p = Person(name: "Alice")
printDescription(item: p)
medium
A. Missing return type in describe() method
B. Function printDescription is missing parameter label
C. Generic constraint syntax is incorrect
D. Person does not conform to Describable protocol

Solution

  1. Step 1: Check protocol conformance of Person

    Person struct does not declare conformance to Describable or implement describe().
  2. Step 2: Understand generic constraint usage

    printDescription requires T to conform to Describable; passing Person causes compile error.
  3. Final Answer:

    Person does not conform to Describable protocol -> Option D
  4. Quick Check:

    Type must conform to protocol to satisfy constraint [OK]
Hint: Check if type implements protocol before passing to constrained function [OK]
Common Mistakes:
  • Assuming protocol conformance is automatic
  • Ignoring missing method implementations
  • Misreading generic constraint syntax
5. Given two protocols:
protocol Identifiable {
    var id: String { get }
}
protocol Nameable {
    var name: String { get }
}

How do you declare a generic function that accepts a type conforming to both Identifiable and Nameable?
hard
A. func process(_ item: T) {}
B. Both C and D are correct
C. func process<T>(item: T) where T: Identifiable, T: Nameable {}
D. func process(_ item: T) {}

Solution

  1. Step 1: Understand multiple protocol constraints syntax

    Swift allows multiple constraints using & inside angle brackets or multiple where clauses.
  2. Step 2: Analyze options

    func process(_ item: T) {} uses & syntax correctly. func process<T>(item: T) where T: Identifiable, T: Nameable {} uses where clause with multiple constraints correctly. func process(_ item: T) {} is invalid syntax.
  3. Final Answer:

    Both func process<T: Identifiable & Nameable> and func process<T> where T: Identifiable, T: Nameable are correct -> Option B
  4. Quick Check:

    Multiple constraints: & or where clause [OK]
Hint: Use & or where clause for multiple protocol constraints [OK]
Common Mistakes:
  • Using comma inside angle brackets incorrectly
  • Confusing syntax for multiple constraints
  • Forgetting to repeat T in where clause
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