Nandin Borjigin
Nandin Borjigin

Reputation: 2154

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

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.

Upvotes: 0

Views: 89

Answers (2)

luk2302
luk2302

Reputation: 57184

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.

Upvotes: 0

Scott Thompson
Scott Thompson

Reputation: 23701

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.

Upvotes: 4

Related Questions