0
0
Swiftprogramming~20 mins

Class declaration syntax in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Class Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
ABuddy
BAnimal
Cname
DCompilation error
Attempts:
2 left
💡 Hint
Look at how the property 'name' is set and accessed.
Predict Output
intermediate
2: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))
ACompilation error
B34
C7
D0
Attempts:
2 left
💡 Hint
The add method returns the sum of two numbers.
Predict Output
advanced
2: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())
AVroom
BBeep
CCompilation error
DRuntime error
Attempts:
2 left
💡 Hint
Check which method is called on the Car instance.
Predict Output
advanced
2: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)
A12.0
B7.0
CCompilation error
D0.0
Attempts:
2 left
💡 Hint
The area is width multiplied by height.
🧠 Conceptual
expert
2: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)
ARuntime error
BAlice
CCompilation error
DBob
Attempts:
2 left
💡 Hint
Classes are reference types in Swift.