0
0
Swiftprogramming~20 mins

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

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