0
0
Swiftprogramming~20 mins

Type aliases for readability in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Typealias Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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))")
APoint coordinates: (x: 3, y: 4)
BPoint coordinates: (4, 3)
CCompilation error
DPoint coordinates: (3, 4)
Attempts:
2 left
💡 Hint
Remember that the tuple elements are accessed by their labels.
Predict Output
intermediate
2: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")
}
Atrue
BFailure
CSuccess
DCompilation error
Attempts:
2 left
💡 Hint
The closure is called with true as argument.
🔧 Debug
advanced
2: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)
AType mismatch: Cannot convert value of type 'Int' to expected argument type 'String'
BCompilation error: Missing return in function
CRuntime error: Unexpected nil value
DNo error, prints 'Hello, 123!'
Attempts:
2 left
💡 Hint
Check the argument type passed to the function.
🧠 Conceptual
advanced
1:30remaining
Purpose of typealias in Swift
Which of the following best describes the purpose of using typealias in Swift?
ATo provide a new name for an existing type to improve code readability
BTo enforce type safety by restricting variable assignments
CTo define a variable with a fixed value
DTo create a new distinct type that is incompatible with the original type
Attempts:
2 left
💡 Hint
Think about how typealias affects the type system and naming.
📝 Syntax
expert
2: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?
Atypealias StringDict = Dictionary<String, T>
Btypealias StringDict<T> = Dictionary<String, T>
Ctypealias StringDict<T> = [String: T]
Dtypealias StringDict = [String: Any]
Attempts:
2 left
💡 Hint
Remember how to declare generic typealiases with type parameters.