[swift-users] Type inference when assigning the result of reduce to a dictionary

Martin R martinr448 at gmail.com
Tue Oct 4 07:20:35 CDT 2016


I noticed the following when assigning the result of `reduce()` to a dictionary:

    let array = [1, 2, 3]
    var dict: [Int: Int] = [:]
    dict[0] = array.reduce(0, { $0 + $1 }) // (A)
    // error: binary operator '+' cannot be applied to operands of
type 'Int?' and 'Int'
    // dict[0] = array.reduce(0, { $0 + $1 })
    //                             ~~ ^ ~~

It seems that the compiler tries to make the RHS an `Int?` and
therefore infers the type of the initial value `0` and the
accumulating value `$0` as `Int?`.

That is in some sense correct, since the dictionary subscript setter
takes an optional as parameter, in this case `Int?`.

However, the code compiles (and runs as expected) if the trailing
closure syntax is used:

    dict[0] = array.reduce(0) { $0 + $1 } // (B)

and also if the initial value is given as `0` instead of `Int(0)`:

    dict[0] = array.reduce(Int(0), { $0 + $1 }) // (C)

My questions are:
- Should (A) compile?
- Why does it make a difference if the trailing closure syntax is used
(A vs. B)?
- Why does it make a difference if the initial value is given as `0`
or `Int(0)` (A vs. C)?

Regards,
Martin


More information about the swift-users mailing list