0
0
Swiftprogramming~20 mins

Calling super for parent behavior in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Super Swift Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Swift code using super?

Consider the following Swift classes. What will be printed when Child().greet() is called?

Swift
class Parent {
    func greet() {
        print("Hello from Parent")
    }
}

class Child: Parent {
    override func greet() {
        super.greet()
        print("Hello from Child")
    }
}

Child().greet()
AHello from Child\nHello from Parent
BHello from Child
CHello from Parent\nHello from Child
DHello from Parent
Attempts:
2 left
💡 Hint

Remember that super.greet() calls the parent class method first.

🧠 Conceptual
intermediate
1:30remaining
Why use super in Swift class methods?

Which of the following best explains why you would call super.method() inside an overridden method?

ATo prevent the parent class method from running.
BTo call the parent class's implementation and add extra behavior in the child class.
CTo call a method from a sibling class.
DTo create a new method unrelated to the parent.
Attempts:
2 left
💡 Hint

Think about how inheritance works and extending behavior.

🔧 Debug
advanced
2:00remaining
What error occurs when calling super in a Swift initializer incorrectly?

Examine this Swift code snippet. What error will it produce?

Swift
class Parent {
    init() {
        print("Parent init")
    }
}

class Child: Parent {
    override init() {
        print(self)
        super.init()
    }
}
AError: Cannot override initializer in subclass
BNo error, prints 'Child init' then 'Parent init'
CError: Missing required initializer
DError: 'super.init()' must be called before accessing self or properties
Attempts:
2 left
💡 Hint

Swift requires calling super.init() before using self in initializers.

📝 Syntax
advanced
1:30remaining
Which option correctly calls the parent method in Swift?

Which of the following is the correct way to call a parent class method named display() inside an overridden method?

Asuper.display()
BParent.display()
Cself.super.display()
Dsuper->display()
Attempts:
2 left
💡 Hint

Remember the Swift syntax for calling parent methods.

🚀 Application
expert
2:30remaining
What is the final value of count after calling increment() twice?

Given these Swift classes, what is the value of count after Child().increment() is called twice?

Swift
class Parent {
    var count = 0
    func increment() {
        count += 1
    }
}

class Child: Parent {
    override func increment() {
        super.increment()
        count += 2
    }
}

let obj = Child()
obj.increment()
obj.increment()
print(obj.count)
A6
B4
C2
D8
Attempts:
2 left
💡 Hint

Each call adds 1 from super.increment() and 2 more in Child.increment().