Bird
Raised Fist0
Swiftprogramming~20 mins

Associated types in protocols in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Associated Types Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of protocol with associated type and conforming struct
What is the output of this Swift code when run?
Swift
protocol Container {
    associatedtype Item
    var items: [Item] { get }
    func firstItem() -> Item?
}

struct IntContainer: Container {
    var items: [Int]
    func firstItem() -> Int? {
        return items.first
    }
}

let container = IntContainer(items: [10, 20, 30])
print(container.firstItem() ?? 0)
A20
B10
Cnil
DCompilation error
Attempts:
2 left
💡 Hint
Look at what the firstItem() function returns from the items array.
❓ Predict Output
intermediate
2:00remaining
Output of generic function using protocol with associated type
What will be printed by this Swift code?
Swift
protocol Summable {
    associatedtype Number
    var values: [Number] { get }
    func sum() -> Number
}

struct IntSum: Summable {
    var values: [Int]
    func sum() -> Int {
        values.reduce(0, +)
    }
}

func printSum<T: Summable>(_ container: T) {
    print(container.sum())
}

let intSum = IntSum(values: [1, 2, 3, 4])
printSum(intSum)
A0
B1234
CCompilation error due to associatedtype
D10
Attempts:
2 left
💡 Hint
The sum() function adds all elements in values.
🔧 Debug
advanced
2:00remaining
Identify the error in protocol conformance with associated type
Why does this Swift code fail to compile?
Swift
protocol Identifiable {
    associatedtype ID
    var id: ID { get }
}

struct User: Identifiable {
    var id: String
    var name: String
}

struct Product: Identifiable {
    var id: Int
    var price: Double
}

func printID<T: Identifiable>(_ item: T) {
    print(item.id)
}

let user = User(id: "abc123", name: "Alice")
let product = Product(id: 101, price: 9.99)
printID(user)
printID(product)
ANo error, code runs and prints ids
BCompilation error because associatedtype ID is not constrained to a specific type
CCompilation error because protocol Identifiable requires a method, not a property
DRuntime error due to type mismatch in printID
Attempts:
2 left
💡 Hint
Check if the protocol requirements are met by the structs.
📝 Syntax
advanced
2:00remaining
Which option correctly declares a protocol with an associated type and a method using it?
Select the correct Swift syntax for a protocol with an associated type named Element and a method that returns an Element.
A
protocol Container {
    associatedtype Element
    func getElement() -&gt; Element?
}
B
protocol Container {
    typealias Element
    func getElement() -&gt; Element
}
C
protocol Container {
    associatedtype Element
    func getElement() -&gt; Element
}
D
protocol Container {
    associatedtype Element
    func getElement() -&gt; Optional&lt;Element&gt;
}
Attempts:
2 left
💡 Hint
associatedtype declares a placeholder type in protocols.
🚀 Application
expert
2:00remaining
How many items are in the resulting array after filtering with associated type constraint?
Given this Swift code, how many elements does the filtered array contain after applying the filter?
Swift
protocol Filterable {
    associatedtype Item
    var items: [Item] { get }
    func filterItems(_ predicate: (Item) -> Bool) -> [Item]
}

struct StringFilter: Filterable {
    var items: [String]
    func filterItems(_ predicate: (String) -> Bool) -> [String] {
        items.filter(predicate)
    }
}

let filter = StringFilter(items: ["apple", "banana", "cherry", "date"])
let result = filter.filterItems { $0.count > 5 }
print(result.count)
A2
B3
C4
D1
Attempts:
2 left
💡 Hint
Count the strings with more than 5 characters.

Practice

(1/5)
1. What is the main purpose of associatedtype in a Swift protocol?
easy
A. To create a stored property inside the protocol
B. To define a placeholder type that conforming types will specify
C. To implement a method inside the protocol
D. To inherit from another protocol

Solution

  1. Step 1: Understand the role of associatedtype

    The associatedtype keyword declares a placeholder type inside a protocol.
  2. Step 2: Identify how conforming types use it

    Types that adopt the protocol specify the actual type for this placeholder, making the protocol flexible.
  3. Final Answer:

    To define a placeholder type that conforming types will specify -> Option B
  4. Quick Check:

    Associated types = Placeholder type [OK]
Hint: Remember: associatedtype is a placeholder type in protocols [OK]
Common Mistakes:
  • Thinking associatedtype creates stored properties
  • Confusing associatedtype with method implementation
  • Assuming associatedtype inherits protocols
2. Which of the following is the correct syntax to declare an associated type named Item inside a protocol?
easy
A. protocol Example { typealias Item }
B. protocol Example { func Item() }
C. protocol Example { var Item: Int }
D. protocol Example { associatedtype Item }

Solution

  1. Step 1: Recall the syntax for associated types

    The correct keyword to declare an associated type is associatedtype.
  2. Step 2: Match the syntax with options

    protocol Example { associatedtype Item } uses associatedtype Item, which is the correct syntax inside a protocol.
  3. Final Answer:

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

    Syntax for associatedtype = protocol Example { associatedtype Item } [OK]
Hint: Use 'associatedtype' keyword, not 'typealias' for protocols [OK]
Common Mistakes:
  • Using typealias instead of associatedtype
  • Declaring associated type as a variable
  • Trying to declare associated type as a function
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]
    }
}

What is the type of Item for IntStack?
medium
A. String
B. Double
C. Int
D. Any

Solution

  1. Step 1: Identify the associated type in the protocol

    The protocol Container has an associated type Item.
  2. Step 2: Check the conforming type's implementation

    IntStack uses an array of Int and its append method accepts Int. So, Item is Int.
  3. Final Answer:

    Int -> Option C
  4. Quick Check:

    Associated type Item = Int in IntStack [OK]
Hint: Look at the type used in methods and properties for Item [OK]
Common Mistakes:
  • Assuming Item is String by default
  • Confusing associated type with protocol name
  • Ignoring the concrete type used in the struct
4. Given the following code, what is the error?
protocol Container {
    associatedtype Item
    func append(_ item: Item)
}

struct StringStack: Container {
    var items = [String]()
    func append(_ item: Int) {
        items.append(String(item))
    }
}
medium
A. append method parameter type does not match associated type
B. Missing mutating keyword on append method
C. Associated type Item is not specified
D. items array type mismatch

Solution

  1. Step 1: Check the protocol's associated type and method

    The protocol expects append(_ item: Item) where Item is the associated type.
  2. Step 2: Compare with struct's append method

    StringStack has append(_ item: Int), but Item should be String because items is an array of String.
  3. Step 3: Identify mismatch

    The parameter type Int does not match the expected String associated type.
  4. Final Answer:

    append method parameter type does not match associated type -> Option A
  5. Quick Check:

    Parameter type mismatch = append method parameter type does not match associated type [OK]
Hint: Check method parameter matches associated type exactly [OK]
Common Mistakes:
  • Forgetting to mark append as mutating
  • Ignoring parameter type mismatch
  • Assuming associated type is Int automatically
5. You want to create a protocol PairContainer with two associated types First and Second. You want a function swap() that swaps the two values inside a conforming struct. Which of the following is the correct way to declare the protocol and implement swap() in a struct?
hard
A. protocol PairContainer { associatedtype First associatedtype Second var first: First { get set } var second: Second { get set } mutating func swap() } struct Pair: PairContainer { var first: Int var second: Int mutating func swap() { (first, second) = (second, first) } }
B. protocol PairContainer { associatedtype First associatedtype Second var first: First { get } var second: Second { get } func swap() } struct Pair: PairContainer { var first: Int var second: Int func swap() { let temp = first first = second second = temp } }
C. protocol PairContainer { associatedtype First associatedtype Second var first: First { get set } var second: Second { get set } func swap() } struct Pair: PairContainer { var first: Int var second: Int mutating func swap() { (first, second) = (second, first) } }
D. protocol PairContainer { associatedtype First associatedtype Second var first: First { get set } var second: Second { get set } mutating func swap() } struct Pair: PairContainer { var first: Int var second: Int func swap() { (first, second) = (second, first) } }

Solution

  1. Step 1: Define protocol with mutable properties and mutating method

    The protocol requires first and second as get/set properties and a mutating func swap() to modify them.
  2. Step 2: Implement struct with matching mutating swap method

    The struct Pair has mutable first and second properties and a mutating func swap() that swaps values correctly.
  3. Step 3: Check other options for errors

    protocol PairContainer { associatedtype First associatedtype Second var first: First { get } var second: Second { get } func swap() } struct Pair: PairContainer { var first: Int var second: Int func swap() { let temp = first first = second second = temp } }'s properties are get-only and swap is non-mutating, so it cannot modify properties. protocol PairContainer { associatedtype First associatedtype Second var first: First { get set } var second: Second { get set } func swap() } struct Pair: PairContainer { var first: Int var second: Int mutating func swap() { (first, second) = (second, first) } } has non-mutating protocol method but mutating struct method, mismatch. protocol PairContainer { associatedtype First associatedtype Second var first: First { get set } var second: Second { get set } mutating func swap() } struct Pair: PairContainer { var first: Int var second: Int func swap() { (first, second) = (second, first) } } has mutating protocol method but non-mutating struct method, mismatch.
  4. Final Answer:

    Protocol with { get set } properties and mutating func swap(), struct with mutating func swap() -> Option A
  5. Quick Check:

    Mutating methods and get/set properties = protocol PairContainer { associatedtype First associatedtype Second var first: First { get set } var second: Second { get set } mutating func swap() } struct Pair: PairContainer { var first: Int var second: Int mutating func swap() { (first, second) = (second, first) } } [OK]
Hint: Mutating methods must be marked mutating in protocol and struct [OK]
Common Mistakes:
  • Not marking swap as mutating in protocol or struct
  • Using get-only properties when set is needed
  • Mismatch between protocol and struct method mutability
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