Search code examples
swiftstructprotocols

Function call causes an infinite recursion


I am struggling how to conform to a protocol in an extension of a struct. Here's my code:

public protocol Foo {
    var index: Int { get set }
}

struct Bar {
    // ...
}

extension Bar: Foo {
    public var index: Int {
        get {
            return 0
        }
        set {
            self.index = newValue <== warning
        }
    }
}

I get this warning:

Function call causes an infinite recursion

How can I solve this?


Solution

  • The biggest issue is that an extension can't declare a stored property. If you attempt to add a property to a struct extension, it would need to be a computed property (which is what you have attempted in your question's code. The problem with the computed property is you don't have anywhere good to store the set value.

    The simplest solution is to add index directly to the Bar struct. Then you can either directly conform to Foo or you can add the extension to conform to Foo.

    Option 1:

    struct Bar: Foo {
        var index: Int
    }
    

    Option 2:

    struct Bar {
        var index: Int
    }
    
    extension Bar: Foo {} // This works because Bar already has index