Here's some explaination.
-
Dictionary
is a collection of key/value pair.
When you use map
/reduce
/sort
functions on them you'll notice that Dictionary
will use (key: Key, value: Value)
.
-
sorted(by:)
takes a closure that takes 2 parameters, left-hand-side and right-hand-side which are elements you want to compare. You tell the algorithm if lhs
should precede rhs
.
That is
data.sorted(by: { lhs, rhs in /* true if lhs should precede rhs */ })
that's why [1, 2, 4, 5, 3].sorted(by: <)
and [1, 2, 4, 5, 3].sorted(by: >)
returns ascending and descending collection respectively.
Now to combine both together, you have values
which is a collection of (key: Breakfast, value: Bool)
and you want to sort them lexicographically by key
, so you compare them by their String
value of the Breakfast
which will be the same as the name of the enum.
If you're to write a full code, it'd look like this
// type of lhs and rhs are the type of collection's *element*
values.sorted { (lhs: (key: Breakfast, value: Bool), rhs: (key: Breakfast, value: Bool)) in
let leftBreakfast = lhs.key, rightBreakfast = rhs.key
let leftString = leftBreakfast.rawValue, rightString = rightBreakfast.rawValue
return leftString < rightString // Compare lexicographically
}
With some key-stroke optimization, it becomes
values.sorted { lhs, rhs in // omit type, swift can infer that
return lhs.keys.rawValue < rhs.keys.rawValue // get straight to leftString and rightString
}
or better
// Omit argument names, the first one becomes $0, the second one becomes $1
// Also omit "return"
// Since we put it in `for-in`, we need to put closure back inside parentheses.
values.sorted(by: { $0.keys.rawValue < $1.keys.rawValue })
Eventually you can just get straight to the last version. It'd become second nature in to time.
You could also create a special type that handle all this like @toph42 said. Depending of the frequency that you use this stuff that could be a better choice.
Hmm, arg
was the name used by a fix-it in ye olde Swift. I guess I sticked with that ever since.
PS
I don't see someone mention ppl like thst often [Lantua](/u/Lantua)
. I generally see @Lantua
. Quite interesting that the forum still notifies me.