Bird
Raised Fist0
Swiftprogramming~20 mins

Protocol with associated types 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 a protocol with associated type conformance
What is the output of this Swift code using a protocol with an associated type?
Swift
protocol Container {
    associatedtype Item
    mutating func append(_ item: Item)
    func count() -> Int
    subscript(i: Int) -> Item { get }
}

struct IntStack: Container {
    var items = [Int]()
    mutating func append(_ item: Int) {
        items.append(item)
    }
    func count() -> Int {
        items.count
    }
    subscript(i: Int) -> Int {
        items[i]
    }
}

var stack = IntStack()
stack.append(10)
stack.append(20)
print(stack.count())
print(stack[1])
A2\n20
B1\n10
C2\n10
D1\n20
Attempts:
2 left
💡 Hint
Think about how many items are appended and what is at index 1.
🧠 Conceptual
intermediate
1:30remaining
Understanding associatedtype constraints
Given the protocol below, which statement about the associatedtype is true?
Swift
protocol Identifiable {
    associatedtype ID: Comparable
    var id: ID { get }
}
AThe associatedtype ID must be an Int.
BThe associatedtype ID must conform to Comparable, so any type used must support comparison.
CThe associatedtype ID must be a class type.
DThe associatedtype ID can be any type without restrictions.
Attempts:
2 left
💡 Hint
Look at the ': Comparable' part in the associatedtype declaration.
🔧 Debug
advanced
2:00remaining
Identify the error in protocol with associated type usage
What error will this Swift code produce?
Swift
protocol Container {
    associatedtype Item
    mutating func append(_ item: Item)
}

struct StringStack: Container {
    var items = [String]()
    mutating func append(_ item: Int) {
        items.append(String(item))
    }
}
AMissing mutating keyword on append method
BNo error, code compiles successfully
CCannot convert value of type 'Int' to expected argument type 'String'
DType 'StringStack' does not conform to protocol 'Container' because 'append' parameter type does not match associatedtype 'Item'
Attempts:
2 left
💡 Hint
Check the parameter type of append compared to the associatedtype Item.
📝 Syntax
advanced
2:00remaining
Correct syntax for protocol with associated type and default implementation
Which option correctly defines a protocol with an associated type and provides a default implementation for a method?
A
protocol Summable {
    associatedtype Number
    func sum(_ a: Number, _ b: Number) -> Number
}
extension Summable {
    func sum(_ a: Number, _ b: Number) -> Number {
        return a - b
    }
}
B
protocol Summable {
    associatedtype Number
    func sum(_ a: Number, _ b: Number) -> Number
}
extension Summable {
    func sum(a: Number, b: Number) -> Number {
        return a + b
    }
}
C
protocol Summable {
    associatedtype Number
    func sum(_ a: Number, _ b: Number) -> Number
}
extension Summable {
    func sum(_ a: Number, _ b: Number) -> Number {
        return a + b
    }
}
D
protocol Summable {
    associatedtype Number
    func sum(_ a: Number, _ b: Number) -> Number
}
extension Summable {
    func sum(_ a: Number, _ b: Number) -> Number {
        return a * b
    }
}
Attempts:
2 left
💡 Hint
Check method signature and operator used in default implementation.
🚀 Application
expert
2:30remaining
Implement a generic function using protocol with associated types
Which option correctly implements a generic function that takes any Container and returns the first item?
Swift
protocol Container {
    associatedtype Item
    func count() -> Int
    subscript(i: Int) -> Item { get }
}

func firstItem<C: Container>(_ container: C) -> C.Item? {
    // Fill in the blank
}
Areturn container.count() > 0 ? container[0] : nil
Breturn container.count > 0 ? container[0] : nil
Creturn container[0]
Dreturn container.first
Attempts:
2 left
💡 Hint
Check how to safely access the first element using count and subscript.

Practice

(1/5)
1.

What is the main purpose of a protocol with an associated type in Swift?

easy
A. To allow protocols to have stored properties
B. To create a fixed type that all conforming types must use
C. To enable inheritance from multiple classes
D. To define a blueprint with a placeholder type that conforming types specify

Solution

  1. Step 1: Understand what associated types do

    Associated types act as placeholders in protocols, letting conforming types specify the actual type.
  2. Step 2: Compare options

    To define a blueprint with a placeholder type that conforming types specify correctly describes this flexibility. Options A, B, and D are incorrect because protocols don't fix types, can't have stored properties, and don't enable class inheritance.
  3. Final Answer:

    To define a blueprint with a placeholder type that conforming types specify -> Option D
  4. Quick Check:

    Associated type = Placeholder type in protocol [OK]
Hint: Remember: associated types are placeholders for flexible types [OK]
Common Mistakes:
  • Thinking associated types fix the type for all conformers
  • Confusing protocols with classes regarding stored properties
  • Believing protocols support multiple inheritance
2.

Which of the following is the correct syntax to declare an associated type named Item inside a protocol?

easy
A. protocol Example { associatedtype Item }
B. protocol Example { typealias Item }
C. protocol Example { var Item: Type }
D. protocol Example { type Item }

Solution

  1. Step 1: Recall syntax for associated types

    In Swift, the keyword to declare an associated type inside a protocol is associatedtype.
  2. Step 2: Check options

    protocol Example { associatedtype Item } uses associatedtype Item, which is correct. protocol Example { typealias Item } uses outdated typealias which is invalid here. Options C and D are incorrect syntax.
  3. Final Answer:

    protocol Example { associatedtype Item } -> Option A
  4. Quick Check:

    Use 'associatedtype' keyword for associated types [OK]
Hint: Use 'associatedtype' keyword to declare associated types [OK]
Common Mistakes:
  • Using 'typealias' instead of 'associatedtype' inside protocols
  • Trying to declare associated types as variables
  • Omitting the keyword entirely
3.

Consider the following Swift code:

protocol Container {
    associatedtype Item
    func append(_ item: Item)
    var count: Int { get }
    subscript(i: Int) -> Item { get }
}

struct IntStack: Container {
    var items = [Int]()
    mutating func append(_ item: Int) {
        items.append(item)
    }
    var count: Int { items.count }
    subscript(i: Int) -> Int { items[i] }
}

var stack = IntStack()
stack.append(10)
stack.append(20)
print(stack[1])

What will be the output?

medium
A. 10
B. 20
C. Index out of range error
D. Compilation error due to missing associated type

Solution

  1. Step 1: Understand the Container protocol and IntStack

    The protocol requires an associated type Item and methods to append, count, and subscript. IntStack conforms with Item as Int.
  2. Step 2: Trace the code execution

    We append 10, then 20 to the stack. The stack items array is [10, 20]. Accessing stack[1] returns the second element, which is 20.
  3. Final Answer:

    20 -> Option B
  4. Quick Check:

    stack[1] = 20 [OK]
Hint: Remember arrays are zero-indexed; stack[1] is second element [OK]
Common Mistakes:
  • Confusing index 1 with index 0
  • Expecting a compilation error due to associated type
  • Assuming append doesn't work because of protocol
4.

Identify the error in this Swift code snippet:

protocol DataSource {
    associatedtype Data
    func fetch() -> Data
}

struct IntSource: DataSource {
    typealias Data = Int
    func fetch() -> String {
        return "Hello"
    }
}
medium
A. fetch() return type does not match associated type Data
B. Missing explicit associated type declaration in IntSource
C. Protocols cannot have functions with return types
D. Structs cannot conform to protocols with associated types

Solution

  1. Step 1: Analyze the protocol and struct

    The protocol DataSource has an associated type Data and requires fetch() returning Data.
  2. Step 2: Check IntSource conformance

    IntSource specifies typealias Data = Int but implements fetch() returning String, which does not match the associated type Data.
  3. Step 3: Identify mismatch

    Data is explicitly set to Int, but fetch() returns String, this is a mismatch causing a compile error.
  4. Final Answer:

    fetch() return type does not match associated type Data -> Option A
  5. Quick Check:

    Return type must match associated type [OK]
Hint: Ensure function return matches associated type exactly [OK]
Common Mistakes:
  • Forgetting to specify associated type explicitly
  • Assuming return type can differ from associated type
  • Thinking structs can't conform to such protocols
5.

You want to create a generic function printFirstItem that accepts any type conforming to the Container protocol below and prints its first item. Which is the correct way to write this function?

protocol Container {
    associatedtype Item
    var count: Int { get }
    subscript(i: Int) -> Item { get }
}
hard
A. func printFirstItem(_ container: Container<Item>) { print(container[0]) }
B. func printFirstItem(_ container: Container) { print(container[0]) }
C. func printFirstItem(_ container: C) { print(container[0]) }
D. func printFirstItem<C>(_ container: C) where C: Container, C.Item == String { print(container[0]) }

Solution

  1. Step 1: Understand protocol with associated type usage

    Protocols with associated types cannot be used as concrete types directly, so Container alone is invalid as a parameter type.
  2. Step 2: Analyze options

    func printFirstItem(_ container: C) { print(container[0]) } uses a generic parameter constrained to Container, which is correct. func printFirstItem(_ container: Container) { print(container[0]) } tries to use protocol as a type directly, which is invalid. func printFirstItem(_ container: Container<Item>) { print(container[0]) } uses invalid syntax. func printFirstItem<C>(_ container: C) where C: Container, C.Item == String { print(container[0]) } adds an extra constraint on Item being String, which is unnecessary here.
  3. Final Answer:

    func printFirstItem(_ container: C) { print(container[0]) } -> Option C
  4. Quick Check:

    Use generics with protocol constraints for associated types [OK]
Hint: Use generics with protocol constraints for associated types [OK]
Common Mistakes:
  • Trying to use protocol with associated type as a concrete type
  • Incorrect generic syntax
  • Adding unnecessary constraints
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