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-13109] compactMap behaves differently when storing result in an optional variable #55555

Closed
swift-ci opened this issue Jun 29, 2020 · 1 comment
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. standard library Area: Standard library umbrella

Comments

@swift-ci
Copy link
Collaborator

Previous ID SR-13109
Radar None
Original Reporter mishra.shashank35 (JIRA User)
Type Bug
Status Resolved
Resolution Invalid

Attachment: Download

Additional Detail from JIRA
Votes 0
Component/s Standard Library
Labels Bug
Assignee None
Priority Medium

md5: 0cd8401bc530790f3f501949662c68e7

Issue Description:

Consider the following playground code -

//Compact map with optional
let marks = ["86", "45", "thiry six", "76"]
let compactMappedOptional: [Int?] = marks.compactMap{ Int($0) }
print("\(compactMappedOptional)")

Output - [Optional(86), Optional(45), nil, Optional(76)]

Expected Output - [Optional(86), Optional(45), Optional(76)]

compactMap() should return non-optional values only. After casting it to [Int?], getting nil as well.

@CodaFi
Copy link
Member

CodaFi commented Jul 3, 2020

Your type annotation on the variable compactMappedOptional is what is leading to this situation. In order for compactMap to yield [Int?], the inner closure must yield Int??.

If we drop the annotation, or give it the type type inference actually assigns it if allowed to fully reconstruct the type - [Int] instead of [Int?] - you get the expected outcome.

@swift-ci swift-ci transferred this issue from apple/swift-issues Apr 25, 2022
This issue was closed.
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. standard library Area: Standard library umbrella
Projects
None yet
Development

No branches or pull requests

2 participants