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 with struct
What is the output of this Swift code using
typealias for a custom name?Swift
struct Point { var x: Int var y: Int } typealias Coordinate = Point let p: Coordinate = Coordinate(x: 3, y: 4) print("x: \(p.x), y: \(p.y)")
Attempts:
2 left
💡 Hint
Remember that typealias just creates a new name for an existing type.
✗ Incorrect
The typealias 'Coordinate' is just another name for 'Point'. So creating a Coordinate instance is the same as creating a Point instance. The values x=3 and y=4 are printed as expected.
❓ Predict Output
intermediate2:00remaining
Output of typealias with function type
What will this Swift code print when using
typealias for a function type?Swift
typealias Operation = (Int, Int) -> Int func add(_ a: Int, _ b: Int) -> Int { return a + b } let op: Operation = add print(op(5, 7))
Attempts:
2 left
💡 Hint
A typealias for a function type can be used to declare variables holding functions.
✗ Incorrect
The typealias 'Operation' defines a function type taking two Ints and returning an Int. The function 'add' matches this type. Calling op(5,7) returns 12.
❓ Predict Output
advanced2:00remaining
Output of nested typealias usage
What is the output of this Swift code using nested typealias inside a struct?
Swift
struct Container { typealias Item = String var items: [Item] } let c = Container(items: ["apple", "banana"]) print(c.items[1])
Attempts:
2 left
💡 Hint
Typealias inside a struct can be used as a shorthand for types used in the struct.
✗ Incorrect
The typealias 'Item' is String. The array contains two strings. Accessing index 1 returns 'banana'.
❓ Predict Output
advanced2:00remaining
Output of typealias with tuple type
What will this Swift code print when using
typealias for a tuple type?Swift
typealias NameAge = (name: String, age: Int) let person: NameAge = (name: "John", age: 30) print("\(person.name) is \(person.age) years old")
Attempts:
2 left
💡 Hint
Typealias can be used to name tuple types for easier reuse.
✗ Incorrect
The typealias 'NameAge' names a tuple type with named elements. Printing person.name and person.age works as expected.
❓ Predict Output
expert3:00remaining
Output of typealias with generic type aliasing
What is the output of this Swift code using a generic typealias?
Swift
typealias Pair<T> = (first: T, second: T) let numbers: Pair<Int> = (first: 10, second: 20) let words: Pair<String> = (first: "hello", second: "world") print(numbers.first + numbers.second) print(words.first + " " + words.second)
Attempts:
2 left
💡 Hint
Generic typealias can create reusable tuple types with different element types.
✗ Incorrect
The generic typealias 'Pair' defines a tuple with two elements of type T. For Int, adding 10 + 20 gives 30. For String, concatenation with space prints 'hello world'.