Introduction
Method defined on Extension
seems to override the default method when default values
are used.
Example
import Foundation
protocol X {
func say(sentence: String)
}
extension X {
func say(sentence: String = "Hello Jessy") {
print("X : \(sentence)")
}
}
struct A: X {
func say(sentence: String = "I'm fine, you ?") {
print("A : \(sentence)")
}
}
let speaker: X = A()
speaker.say(sentence: "Hello World") // Should print -> A: Hello World
speaker.say() // Should print -> A: I'm fine, you ?
Debug Console
A : Hello World
X : Hello Jessy
As you can see above, the implementation method called when default values are used is the implementation defined into the extension
rather than the one defined on the struct
.
This behavior is weird, implementation should be overridden by the struct
.
Let's try without default values
protocol X {
func say(sentence: String)
}
extension X {
func say(sentence: String) {
print("X : \(sentence)")
}
}
struct A: X {
func say(sentence: String) {
print("A : \(sentence)")
}
}
let speaker: X = A()
speaker.say(sentence: "Hello World")
speaker.say(sentence: "I'm fine, you ?")
A : Hello World
A : I'm fine, you ?
In this case, speaker
call the right initialization defined into the A
struct.
The question is: Is this a bug or a feature ?
What should be expected
import Foundation
protocol X {
func say(sentence: String)
}
extension X {
func say(sentence: String = "Hello Jessy") {
print("X : \(sentence)")
}
}
struct A: X {
func say(sentence: String = "I'm fine, you ?") {
print("A : \(sentence)")
}
}
let speaker: X = A()
speaker.say(sentence: "Hello World") // Should print -> A: Hello World
speaker.say() // Should print -> A: I'm fine, you ?
Debug Console
A : Hello World
X : I'm fine, you ?
Improvement
We need to bring some coherence between the behavior with/without default values.
Since the method is declared into the protocol
, the struct
instance must call its own method and not the one defined into the extension
.
On our first example speaker.say()
should print A: I'm fine, you ?
instead of Hello Jessy
.