0
0
Swiftprogramming~20 mins

Convenience initializers in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Convenience Initializer Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a class with convenience initializer
What will be printed when the following Swift code runs?
Swift
class Vehicle {
    var wheels: Int
    init(wheels: Int) {
        self.wheels = wheels
    }
    convenience init() {
        self.init(wheels: 4)
    }
}

let car = Vehicle()
print(car.wheels)
A4
B0
CCompilation error
Dnil
Attempts:
2 left
💡 Hint
Remember that the convenience initializer calls the designated initializer with 4 wheels.
Predict Output
intermediate
2:00remaining
Value of property after using convenience initializer with parameters
What is the value of 'name' after running this Swift code?
Swift
class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
    convenience init() {
        self.init(name: "Anonymous")
    }
}

let p = Person()
print(p.name)
A""
B"Anonymous"
Cnil
DCompilation error
Attempts:
2 left
💡 Hint
The convenience initializer sets the name to "Anonymous".
Predict Output
advanced
2:00remaining
Output of subclass using convenience initializer
What will be printed when this Swift code runs?
Swift
class Animal {
    var species: String
    init(species: String) {
        self.species = species
    }
    convenience init() {
        self.init(species: "Unknown")
    }
}

class Dog: Animal {
    var name: String
    init(name: String) {
        self.name = name
        super.init(species: "Dog")
    }
    convenience init() {
        self.init(name: "Buddy")
    }
}

let dog = Dog()
print(dog.name + " is a " + dog.species)
ABuddy is a Dog
BBuddy is a Unknown
CRuntime error
DCompilation error
Attempts:
2 left
💡 Hint
The Dog convenience initializer calls init(name: "Buddy") which sets species to "Dog".
Predict Output
advanced
2:00remaining
Error type from incorrect convenience initializer
What error does this Swift code produce?
Swift
class Box {
    var size: Int
    init(size: Int) {
        self.size = size
    }
    convenience init() {
        self.size = 10
    }
}
AError: Convenience initializer cannot have parameters
BNo error, compiles fine
CError: Missing return type
DError: 'self' used before calling designated initializer
Attempts:
2 left
💡 Hint
In convenience initializers, you must call a designated initializer before setting properties.
🧠 Conceptual
expert
3:00remaining
Correct order of initialization in Swift convenience initializer
Which sequence correctly describes the order of steps when a convenience initializer is called in Swift?
A1, 3, 2, 4
B2, 1, 3, 4
C1, 2, 3, 4
D3, 2, 1, 4
Attempts:
2 left
💡 Hint
Convenience initializers must call a designated initializer before properties are set.