Example code in SE-0269

Hi @Jumhyn may I ask a quesiton about the following example code in SE-0269? The code doesn't look correct to me. Since the method() method is non-mutating, the self implicitly passed to the cloure in it has to be immutable. If so, how could x += 1 work?

I tried the code in playground and the compiler did emit "Left side of mutating operator isn't mutable: 'self' is immutable" error. Is this a code "copy and paste" error in the proposal or am I missing something?

# The value type example in introduction section

struct Test {
    var x = 0
    func execute(_ work: @escaping () -> Void) {
        work()
    }
    func method() {
        execute { 
            x += 1
        }
    }
}
1 Like

Looks like a copy and paste error to me. There's no way that self can be mutated inside the closure as-is. Escaping closures cannot modify a captured value type as the value is copied into the closure when it's captured.

The example needs to be changed to a read-only demonstration of the feature to compile.

struct Test {
    var x = 0
    func execute(_ work: @escaping () -> Void) {
        work()
    }
    func method() {
        execute { 
            print(x)
        }
    }
}

Yeah, this is just a drafting error. The "value type" rule was added in a later draft of the proposal and, as @bradleymackey suggests, a poorly-checked copy-paste led to this issue.

I've opened a PR to correct this here. Thank you both!

2 Likes
Terms of Service

Privacy Policy

Cookie Policy