Default values in override funcs

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()
let b = B()
let c: A = B()

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 ?

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

See [Pitch] Allow default parameter overrides - #2 by xwu for an explanation for 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 '') and emits that.

1 Like