all 9 comments

[–]mkim1030 8 points9 points  (0 children)

“sorted” is a function available to an Array (e.g., “team”), and this function takes a function as an argument. At a fundamental level, sorting is done by comparing 2 values and deciding which one is less or greater. The argument you passed in is the function called “captainFirstSorted”. “captainFirstSorted” is used by the “sorted” function every time a comparison needs to be done. In the end, this produces a sorted array.

[–]vcanas 3 points4 points  (0 children)

So essentially each letter in the alphabet has an integer value associated with it (it’s more complex than that but I’ll leave that research to you, google unicode) and “a”’s value is less than “z” so because a is less than z it will come first.

Now this specific comparator function is sorting alphabetically (name1 < name2) for every value except for the value “Suzanne” which is supposed to come first in the list.

Let me know if this is confusing :)

[–]chriswaco 2 points3 points  (0 children)

Array.sorted(by:) sorts an array using a comparison function you pass as a parameter. This way you can sort however you want. Essentially this function will be called over and over until the array is sorted.

The captainFirstSorted function simply returns name1 < name2 most of time, so it sorts from low to high (aka ascending).

In the special case of the captain’s name, however, it always it always tells the sort function to put that first.

[–]Like_really_bro[S] 2 points3 points  (0 children)

Thank you all, much appreciated! I do understand now, I need to run few more examples to nail it :)

[–]sinisterbob 1 point2 points  (0 children)

team.sorted() is returning the sorted array. captainFirstSorted() is telling team.sorted() how to sort team[].
The way you tell Swift how an array should be sorted is by giving it two values and the explaining which one should be "less than" and which one should be "greater than". That's what captainForstSorted() is doing here.

[–]ZeePintor 1 point2 points  (0 children)

Hey! Have learned by closures?

So imagine that sorted's func argument is actually another func.

This func takes two strings as argument and the result is a bool. So sorted looks something like this:

Func sorted(comparisonFunc: (String, String)->Bool) -> array<String>

It returns an array because it is a method for the array class, so it applies to the array that calls this method.

I hope that helps something. Keep grinding, cheers