Created
April 22, 2019 19:59
-
-
Save mfaani/55479733b2670661884dc5aa6e1ffbc2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://stackoverflow.com/questions/55446713/true-false-question-about-swift-subclass-superclass | |
class Person { | |
var age : Int? | |
func incrementAge() { | |
guard age != nil else { | |
age = 1 | |
return | |
} | |
age! += 1 | |
} | |
func eat() { | |
print("eat popcorn") | |
} | |
} | |
var p1 = Person() | |
p1.incrementAge() // works fine | |
class Boy : Person{ | |
override func incrementAge() { | |
age! += 2 | |
} | |
} | |
var b1 = Boy() | |
b1.incrementAge() // crashes, becasuse you literally overrode the behavior!!! | |
class GoodBoy : Person{ | |
override func incrementAge() { | |
super.incrementAge() | |
age! += 2 | |
} | |
} | |
var b2 = GoodBoy() | |
b2.incrementAge() // works fine. | |
class AlternateGoodBoy : Person{ | |
override func incrementAge() { | |
guard age != nil else { | |
age = 1 | |
return | |
} | |
age! += 2 | |
} | |
} | |
var b3 = AlternateGoodBoy() | |
b3.incrementAge() // works fine. | |
class Girl : Person{ | |
override func eat() { | |
print("eat hotdog") | |
} | |
} | |
var g1 = Girl() | |
g1.eat() // doesn't crash, even though you overrode the behavior. It doesn't crash because the call to super ISN'T critical | |
class Dad : Person { | |
var moneyInBank = 0 | |
override func incrementAge() { | |
super.incrementAge() | |
addMoneyToRetirementFunds() | |
} | |
func addMoneyToRetirementFunds() { | |
moneyInBank += 2000 | |
} | |
} | |
var d1 = Dad() | |
d1.incrementAge() | |
print(d1.moneyInBank) // 2000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment