4 ms·
Feels backwards to me, at least as a gut feel. groceriesByDepartment.mapValues { items in items.count } vs e.g. Ruby (or at least close, it has been a whi
by Groxx 9y ago
Feels backwards to me, at least as a gut feel.
groceriesByDepartment.mapValues { items in items.count }
vs e.g. Ruby (or at least close, it has been a while):
groceriesByDepartment.map { |item| item.count }
The "in" makes it feel like you're calling "items.count" on...? and then getting the "items" from it (since it sorta implies that items are in items.count, which seems like nonsense).
E.g. this reads more naturally to me:
groceriesByDepartment.mapValues { item.count in item }
otherStuff.do { a.value + b.value in a, b }
which would also move the "what it does" further to the left, rather than having to skip over the argument names (which are frequently obvious in context, and/or something trivial like "it" or "item" or "x").
---
That said, if you consider it as "use 'items' in [a block of code]" it basically makes sense, and I could probably learn to stop worrying, and love the syntax.
- Camillo 9y agoI agree, the examples in the article look terribly confusing. And they're inconsistent with Swift's own for loop syntax: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html https://developer.apple.com/library/content/documentation/Sw... for item in groceries { print item.department } versus: Dictionary(grouping: groceries by: { item in item.department }) The people who chose this syntax probably said "hey, it's VARIABLE in EXPRESSION, same thing right?". But the semantics are completely different! In the for loop it's "for PRODUCT in SOURCE": the expression is evaluated first, and the variable is assigned with each of its items in turn. In the lambda or whatever it is, it's "{ SOURCE in PRODUCT }": first the variable is assigned, then the expression is evaluated based on it. The data flow is the opposite! This is just objectively bad language design.
- smitherfield 9y agoI prefer Ruby's syntax too, but Swift also has a shorthand version which is, IMO, usually nicer. groceriesByDepartment.mapValues { $0.count }
- jakobegger 9y agoThe shorthand version doesn‘t let you specify argumen types (only works when they can be inferred)
- mantas 9y agoWhich is vast majority of cases. Unless you work with a lot of legacy ObjC code.
- Groxx 9y agostuff like this always makes me miss Ruby's even-shorter-hand version though :) groceriesByDepartment.mapValues(&:count) # not ruby, but meh