Is this a bug in Xcode or a practice should be avoid by programmer?

94 Views Asked by At

In the first place, I looked for a way to simplify coding by providing default argument values for protocol functions. I took the solution here and then found some fatal subsequence it may bring:

protocol Foo {
    func foo(_ a: Int)
}

extension Foo {
    func foo(_ a: Int = 4) {
        foo(a)
    }
}

struct FooImpl: Foo {
    // empty implementation
}

FooImpl().foo() // will go recursively forever and finally reach the stack limit

I also found that this code would fail to compile in IBM Swift Sandbox thus supposing xcode compiler might be to blame.

2

There are 2 best solutions below

2
On BEST ANSWER

This looks to be valid Swift code that the compiler should accept and execute. That it contains a fatal infinite recursion is a logic error on the part of the programmer.

I don't see anything in the IBM Swift Sandbox to indicate that it handles the code any better, or differently, than Xcode.

0
On

You omitted a very important part of the implementation. If you do this you have to implement foo in FooImpl. If you do not implement it your code is basically equivalent to

protocol Foo {
}

extension Foo {
    func foo(_ a: Int = 4) {
        foo(a)
    }
}

struct FooImpl: Foo {
}

FooImpl().foo()

which obviously creates an infinite loop. If you correctly implement foo you will see the expected behaviour:

protocol Foo {
    func foo(_ a: Int)
}

extension Foo {
    func foo(_ a: Int = 4) {
        foo(a)
    }
}

struct FooImpl: Foo {
    func foo(_ a: Int) {
        print(a)
    }
}

FooImpl().foo()

Both are perfectly valid swift snippets, the only difference is that one actually works, the other will crash. But that is nothing the compiler is supposed to worry about.