0
0
Swiftprogramming~20 mins

Generic subscripts in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Generic Subscript Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of generic subscript accessing dictionary
What is the output of this Swift code using a generic subscript to access dictionary values?
Swift
struct Container {
    private var data = ["a": 1, "b": 2, "c": 3]
    subscript<T>(key: T) -> Int? where T == String {
        return data[key]
    }
}

let container = Container()
print(container["b"] ?? 0)
Anil
BOptional(2)
CCompile-time error
D2
Attempts:
2 left
💡 Hint
The subscript returns an Int? but the print unwraps it with ?? operator.
Predict Output
intermediate
2:00remaining
Generic subscript with multiple constraints output
What will this Swift code print when using a generic subscript constrained to Numeric & Comparable types?
Swift
struct Numbers {
    private var values = [10, 20, 30, 40]
    subscript<T: Numeric & Comparable>(index: T) -> T? {
        guard let i = index as? Int, i < values.count else { return nil }
        return values[i] as? T
    }
}

let nums = Numbers()
print(nums[2] ?? -1)
A30
B-1
Cnil
DRuntime error
Attempts:
2 left
💡 Hint
The subscript converts generic index to Int and returns the value if valid.
🔧 Debug
advanced
2:00remaining
Identify the error in generic subscript declaration
This Swift struct uses a generic subscript but causes a compile error. What is the error?
Swift
struct Box {
    var items = ["apple", "banana"]
    subscript<T>(index: T) -> String {
        return items[index]
    }
}
AMissing return type in subscript
BArray items is not initialized
CCannot subscript array with generic type T without constraint
DSubscript must be static
Attempts:
2 left
💡 Hint
Array subscripts require Int index, generic T is unconstrained.
📝 Syntax
advanced
2:00remaining
Which generic subscript syntax is correct?
Which option shows the correct syntax for a generic subscript in Swift that returns the count of elements for a generic collection?
Asubscript<T: Collection>(item: T) -> Int { return item.count }
Bsubscript<T>(item: T) -> Int where T: Collection { return item.count }
Csubscript<T>(item: T: Collection) -> Int { return item.count }
Dsubscript<T>(item: T) -> Int where T Collection { return item.count }
Attempts:
2 left
💡 Hint
Generic constraints use 'where' clause after return type.
🚀 Application
expert
3:00remaining
Using generic subscripts to access heterogeneous dictionary values
Given this Swift struct with a generic subscript, what will be the output of the print statements?
Swift
struct AnyDict {
    private var dict: [String: Any] = ["int": 42, "str": "hello", "dbl": 3.14]
    subscript<T>(key: String) -> T? {
        return dict[key] as? T
    }
}

let anyDict = AnyDict()
print(anyDict["int"] as Int?)
print(anyDict["str"] as String?)
print(anyDict["dbl"] as Double?)
print(anyDict["missing"] as Int?)
A
Optional(42)
Optional("hello")
Optional(3.14)
nil
B
42
hello
3.14
0
CCompile-time error due to generic subscript
D
Optional(42)
Optional("hello")
Optional(3.14)
Optional(0)
Attempts:
2 left
💡 Hint
The subscript casts Any to requested type and returns optional.