Challenge - 5 Problems
Swift Typealias Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of code using typealias for a tuple
What is the output of this Swift code that uses a typealias for a tuple representing a point?
Swift
typealias Point = (x: Int, y: Int) let p: Point = (x: 3, y: 4) print("Point coordinates: (\(p.x), \(p.y))")
Attempts:
2 left
💡 Hint
Remember that the tuple elements are accessed by their labels.
✗ Incorrect
The typealias Point defines a tuple with named elements x and y. The print statement accesses p.x and p.y correctly, so it outputs the coordinates as (3, 4).
❓ Predict Output
intermediate2:00remaining
Using typealias for closure readability
What will this Swift code print when using a typealias for a closure type?
Swift
typealias CompletionHandler = (Bool) -> Void func performTask(completion: CompletionHandler) { completion(true) } performTask { success in print(success ? "Success" : "Failure") }
Attempts:
2 left
💡 Hint
The closure is called with true as argument.
✗ Incorrect
The performTask function calls the completion closure with true, so the print statement outputs "Success".
🔧 Debug
advanced2:00remaining
Identify the error with typealias usage
What error does this Swift code produce?
Swift
typealias Name = String func greet(name: Name) { print("Hello, \(name)!") } greet(name: 123)
Attempts:
2 left
💡 Hint
Check the argument type passed to the function.
✗ Incorrect
The function expects a String (aliased as Name), but 123 is an Int, causing a type mismatch error at compile time.
🧠 Conceptual
advanced1:30remaining
Purpose of typealias in Swift
Which of the following best describes the purpose of using typealias in Swift?
Attempts:
2 left
💡 Hint
Think about how typealias affects the type system and naming.
✗ Incorrect
Typealias creates a new name for an existing type without creating a new type, helping make code easier to read and understand.
📝 Syntax
expert2:30remaining
Correct syntax for typealias with generic type
Which option shows the correct syntax for defining a typealias for a generic dictionary with String keys and values of any type in Swift?
Attempts:
2 left
💡 Hint
Remember how to declare generic typealiases with type parameters.
✗ Incorrect
Option B correctly declares a generic typealias with a type parameter T. Option B and D are missing generic syntax or use Any instead of generic.