Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SR-2853] Type inference when assigning the result of reduce to a dictionary #45447

Closed
martinr448 opened this issue Oct 4, 2016 · 1 comment
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. compiler The Swift compiler in itself type checker Area → compiler: Semantic analysis

Comments

@martinr448
Copy link

Previous ID SR-2853
Radar None
Original Reporter @martinr448
Type Bug
Environment

Tested with Xcode 8 and 8.1 beta on macOS 10.12.

Additional Detail from JIRA
Votes 0
Component/s Compiler
Labels Bug, TypeChecker
Assignee None
Priority Medium

md5: a8c804c59b4216332161a5c76e7e1006

Issue Description:

This fails to compile:

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?.

However, it compiles if the trailing closure syntax is used:

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

or if the initial value is given as Int(0) instead of 0:

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

I do not know if (A) should compile, but there should not be a difference between (A), (B), and (C).

@martinr448
Copy link
Author

It seems that the bug has been fixed in the meantime. I cannot reproduce the problem with Xcode 9.2 (9C40b) anymore. The statement (A) compiles and behaves as expected:
let array = [1, 2, 3]
var dict: [Int: Int] = [:]
dict[0] = array.reduce(0, { $0 + $1 }) // (A)
print(dict) // [0: 6]

@swift-ci swift-ci transferred this issue from apple/swift-issues Apr 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. compiler The Swift compiler in itself type checker Area → compiler: Semantic analysis
Projects
None yet
Development

No branches or pull requests

1 participant