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 ?
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.