0
0
Swiftprogramming~20 mins

Typealias for custom naming 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 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)")
Ax: 3, y: 4
Bx: 4, y: 3
CCompile error: Cannot assign to typealias
DRuntime error: Unexpected nil value
Attempts:
2 left
💡 Hint
Remember that typealias just creates a new name for an existing type.
Predict Output
intermediate
2: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))
ACompile error: Cannot assign function to typealias
B12
C57
DRuntime error: Function not found
Attempts:
2 left
💡 Hint
A typealias for a function type can be used to declare variables holding functions.
Predict Output
advanced
2: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])
ARuntime error: Index out of range
Bapple
Cbanana
DCompile error: Cannot use typealias inside struct
Attempts:
2 left
💡 Hint
Typealias inside a struct can be used as a shorthand for types used in the struct.
Predict Output
advanced
2: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")
ARuntime error: Missing tuple element
B(John, 30)
CCompile error: Cannot use tuple with typealias
DJohn is 30 years old
Attempts:
2 left
💡 Hint
Typealias can be used to name tuple types for easier reuse.
Predict Output
expert
3: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)
A
30
hello world
B
1020
hello world
CCompile error: Generic typealias not supported
DRuntime error: Cannot add Int and String
Attempts:
2 left
💡 Hint
Generic typealias can create reusable tuple types with different element types.