Error depending on position of closure's inout argument

The following program works as expected (Swift 4.2):

func f(_ op: (Int, inout Int) -> Void) {
    var v = 123
    op(456, &v)
    print(v)
}

f { $1 *= 2 } // Prints 246

But swapping the closure's arguments will result in an error:

func f(_ op: (inout Int, Int) -> Void) {
    var v = 123
    op(&v, 456)
    print(v)
}

f { $0 *= 2 } // ERROR: Contextual closure type '(inout Int, Int) -> Void'
              // expects 2 arguments, but 1 was used in closure body

It seems strange that this should be an error given that the first variant compiled, it too uses only one of the two arguments.

Is this a compiler bug?

Perhaps it has been fixed in Swift 5?
I don't currently have access to Xcode 10.2 beta/Swift 5.

(I know the second variant compiles with eg f { v, _ in v *= 2 } or f { $0 *= $1 } but that is not the point.)

1 Like

Here's a simpler related example:

func f(_ op: (Int, Int) -> Int) {
    print(op(123, 456))
}

f { $1 } // OK
f { $0 } // ERROR

Is this a compiler bug?

Yes, see SR-1528.

Perhaps it has been fixed in Swift 5?

No, not in the latest Swift 5.0 snapshot.

2 Likes
Terms of Service

Privacy Policy

Cookie Policy