0
0
Swiftprogramming~20 mins

Generic type declaration in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Generics Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a generic function with type constraint

What is the output of this Swift code using a generic function constrained to Comparable?

Swift
func findMax<T: Comparable>(_ a: T, _ b: T) -> T {
    return a > b ? a : b
}

let result = findMax(10, 20)
print(result)
A20
B10
CCompilation error due to missing type constraint
DRuntime error
Attempts:
2 left
💡 Hint

Think about which value is greater between 10 and 20.

Predict Output
intermediate
2:00remaining
Output of generic struct with multiple type parameters

What will be printed by this Swift code using a generic struct with two type parameters?

Swift
struct Pair<A, B> {
    var first: A
    var second: B
}

let pair = Pair(first: "Hello", second: 42)
print(pair.first, pair.second)
AHello 42
B42 Hello
CRuntime error
DCompilation error due to missing type constraints
Attempts:
2 left
💡 Hint

Look at the order of the properties in the struct.

🔧 Debug
advanced
2:00remaining
Identify the error in generic class declaration

What error does this Swift code produce?

Swift
class Box<T> {
    var value: T
    init(value: T) {
        self.value = value
    }
}

let box = Box<Int>()
ANo error, code runs fine
BError: Generic type 'Box' requires 2 type parameters
CError: Missing argument for parameter 'value' in call
DError: Cannot infer generic parameter 'T'
Attempts:
2 left
💡 Hint

Check the initializer call and its parameters.

📝 Syntax
advanced
2:00remaining
Which generic declaration is syntactically correct?

Which of the following Swift generic type declarations is syntactically correct?

Astruct Container<T where T: Equatable> { var item: T }
Bstruct Container<T> where T Equatable { var item: T }
Cstruct Container<T Equatable> { var item: T }
Dstruct Container<T: Equatable> { var item: T }
Attempts:
2 left
💡 Hint

Remember the syntax for type constraints in generic declarations.

🚀 Application
expert
3:00remaining
Result of using generic function with protocol and associated type

Given the following Swift code, what is the output?

Swift
protocol Container {
    associatedtype Item
    func add(_ item: Item)
    func count() -> Int
}

class Box<T>: Container {
    private var items = [T]()
    func add(_ item: T) {
        items.append(item)
    }
    func count() -> Int {
        items.count
    }
}

let box = Box<String>()
box.add("Swift")
box.add("Generics")
print(box.count())
A0
B2
CRuntime error
DCompilation error due to missing initializer
Attempts:
2 left
💡 Hint

Consider how many items are added before counting.