sorted(by:)
gives you two elements from the sequence and you return a Bool
indicating if those two elements are in the correct order. The implementation of sorted(by:)
then uses that result to sort the sequence.
You don't really need to know what type of parameters to pass in to sorted(by:)
; Swift takes care of that for you by passing it whatever type the sequence's Element
is. (i.e., if your sequence is [String]
, the closure gets two String
s; if the sequence is [Int]
, the closure gets two Int
s, etc) You also don't need to indicate the closure's return type.
let captainFirstTeam = team.sorted(by: { name1, name2 in
return name1 < name2
})
Heck, you don't even need to name the parameters:
let captainFirstTeam = team.sorted(by: {
return $0 < $1
})
The closure syntax can be reduced even more than that, but that might be a good place to stop for now.
So, basically, if you look at sorted(by:)
's signature in the documentation:
func sorted(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> [Element]
you'll see that the closure takes two items that are whatever type the sequence's Element
s are and returns a Bool
.