[swift-evolution] Protocol extension function overrides the default value in implementations
Grzegorz Leszek
grzesiek.leszek at gmail.com
Mon Jan 18 12:16:19 CST 2016
This is expected behavior.
for p in protocols {
p.printSomething() // Good, Good instead of John, Hahaha
}
is calling method from extension:
extension Good {
func printSomething() { self.printSomething("Good") }
}
this method (for class Name) is calling method guaranteed by protocol :
func printSomething(something: String = "John") {
print(something)
}
and this method is printing Good, because it has a argument. (Default
Parameter Value - John - is not triggered)
More about it:
* video "Protocol-Oriented Programming in Swift" (WWDC 2015 - Session 408)
* Swift Book, section Function, subsection Default Parameter Values
Greg
2016-01-16 12:51 GMT+00:00 肇鑫 via swift-evolution <swift-evolution at swift.org>:
> I got this by discussions in another thread of swift-evolution. The result
> is interesting. I don't know if it should be treat as a bug.
>
> protocol Good {
>
> func printSomething(something:String)
>
> }
>
>
> extension Good {
>
> func printSomething() { self.printSomething("Good") }
>
> }
>
>
> struct Name:Good {
>
> func printSomething(something: String = "John") {
>
> print(something)
>
> }
>
> }
>
>
> struct Talk:Good {
>
> func printSomething(something: String = "Hahaha") {
>
> print(something)
>
> }
>
> }
>
>
> var protocols:[Good] = [Name(), Talk()]
>
>
> for p in protocols {
>
> p.printSomething() // Good, Good instead of John, Hahaha
>
> }
>
>
> As you can see, the final result is "Good, Good", not as I expected "John,
> Hahaha", is that right or is it a bug?
>
>
> zhaoxin
>
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
More information about the swift-evolution
mailing list