Challenge - 5 Problems
Swift Class Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple Swift class instance property
What is the output of this Swift code?
Swift
class Animal { var name: String init(name: String) { self.name = name } } let dog = Animal(name: "Buddy") print(dog.name)
Attempts:
2 left
💡 Hint
Look at how the property 'name' is set and accessed.
✗ Incorrect
The class Animal has a property 'name' initialized with 'Buddy'. Printing dog.name outputs 'Buddy'.
❓ Predict Output
intermediate2:00remaining
Output when accessing a class method
What will this Swift code print?
Swift
class Calculator { func add(_ a: Int, _ b: Int) -> Int { return a + b } } let calc = Calculator() print(calc.add(3, 4))
Attempts:
2 left
💡 Hint
The add method returns the sum of two numbers.
✗ Incorrect
The add method adds 3 and 4, returning 7 which is printed.
❓ Predict Output
advanced2:00remaining
Output of class inheritance and method override
What is the output of this Swift code?
Swift
class Vehicle { func sound() -> String { return "Vroom" } } class Car: Vehicle { override func sound() -> String { return "Beep" } } let myCar = Car() print(myCar.sound())
Attempts:
2 left
💡 Hint
Check which method is called on the Car instance.
✗ Incorrect
Car overrides the sound method to return 'Beep'. So printing myCar.sound() outputs 'Beep'.
❓ Predict Output
advanced2:00remaining
Output of a class with a computed property
What will this Swift code print?
Swift
class Rectangle { var width: Double var height: Double var area: Double { return width * height } init(width: Double, height: Double) { self.width = width self.height = height } } let rect = Rectangle(width: 3, height: 4) print(rect.area)
Attempts:
2 left
💡 Hint
The area is width multiplied by height.
✗ Incorrect
The computed property area returns 3 * 4 = 12.0 which is printed.
🧠 Conceptual
expert2:00remaining
Understanding class reference behavior in Swift
Consider this Swift code. What is the value of 'b.name' after execution?
Swift
class Person { var name: String init(name: String) { self.name = name } } let a = Person(name: "Alice") let b = a b.name = "Bob" print(a.name)
Attempts:
2 left
💡 Hint
Classes are reference types in Swift.
✗ Incorrect
Both 'a' and 'b' refer to the same Person instance. Changing b.name changes a.name too.