mkbrwr
(Mykhailo Tymchyshyn)
1
class A {
func foo(x: Int = 10) {
print("A:", x)
}
}
class B: A {
override func foo(x: Int = 20) {
print("B:", x)
}
}
let a = A()
a.foo()
let b = B()
b.foo()
let c: A = B()
c.foo()
And the output is:
A: 10
B: 20
B: 10
It's clear for first and second call, but the third one is weird. Looks like the func is using default value from superclass for overridden function. Can explain this behaviour ?
ccashman
(Colin Cashman)
2
You are defining C as an instance of an explicit type (A), so when you call foo() you get the behavior of the method as A.
1 Like
Default argument values are emitted at the call site, so the compiler uses the most specific static type information available (that the receiver 'c' has type 'A') to locate a default argument expression ('10' from 'A.foo()') and emits that.
1 Like