IntrepidPursuits/swift-style-guide

Proposal: Flatmap scenarios of preference

Opened this issue · 4 comments

For example

if let url = urlString.flatMap({ NSURL(string: $0) }) { ...

is possibly preferable:

if let urlString = urlString, let url = NSURL(string: $0) { ...

not sure I get the use of flatMap - where is the sequence?

@brightredchilli In this case, it's running on an Optional. There's also a flat map on those since I think they conform to CollectionOfOne or some other weird kind of collection protocol.

I believe anything that boxes a value is considered a collection on some level. This one essentially operates on the unwrapped value if one exists.

This is a proposal by the way, I think it warrants discussion.

yes i would definitely prefer the second style to the first - for one, flatMap should be flattening(which it isn't), and map should produce an array, even if it's an array of one(which it isn't). Is anyone using flatMap in this manner right now?

oh never mind, CollectionOfOne has overrides on flatMap. still feels weird though.