Skip to content

Instantly share code, notes, and snippets.

@ollieatkinson
Created December 12, 2016 11:28
Show Gist options
  • Save ollieatkinson/6f0f24f8ecee2b697e96a67b7783c7db to your computer and use it in GitHub Desktop.
Save ollieatkinson/6f0f24f8ecee2b697e96a67b7783c7db to your computer and use it in GitHub Desktop.
Swift extension with a default parameter - πŸ› bug
protocol Foo {
func foo(_ int: Int)
}
extension Foo {
func foo(_ int: Int = 1) { print("foo") }
func bar() { print("bar") }
}
func testFoo(foo: Foo) {
foo.foo()
foo.bar()
}
struct FooImpl: Foo {
}
struct FooStub: Foo {
func foo(_ int: Int) { print("stubbed foo") }
func bar() { print("stubbed bar") }
}
testFoo(foo: FooImpl())
testFoo(foo: FooStub())
protocol Foo {
func foo(_ int: Int)
}
extension Foo {
func foo() { self.foo(1) }
func foo(_ int: Int) { print("foo (\(int))") }
func bar() { print("bar") }
}
func testFoo(foo: Foo) {
foo.foo()
foo.bar()
}
struct FooImpl: Foo {
}
struct FooStub: Foo {
func foo(_ int: Int) { print("stubbed foo (\(int))") }
func bar() { print("stubbed bar") }
}
testFoo(foo: FooImpl())
testFoo(foo: FooStub())
@KingOfBrian
Copy link

That's interesting @olliatkinson! It definitely is confusing, but (i think) it's operating as intended. I believe there is some thoughts to add default values to protocols so this behavior becomes clearer. Your OverloadExample is the best way to obtain this functionality at this point I believe.

What is happening is testFoo is using direct dispatch to the extension method with the default parameter. The protocol has no way of knowing else to do, so the method in FooStub is never called. If the protocol could state that it needs a default value, the behavior would be more clear, but for now it's not.

I did a quick scan of https://bugs.swift.org/ and didn't see anything, but log a bug there if you want an official opinion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment