func backwards(s1: String, s2: String){ return s1>s2 } let names = ["Aa", "Cc", "Ee", "Dd", "Bb"] var reversed = names.sort(backwards) So we have an array called names, which has a "sort" method. We give "backwards" as a parameter of sort method. But neither we give any parameters for backward(and as i see it should take two strings), nor the return value of "backwards" function affect the sort method(i've tried names.sort(true) and names.sort(false) and it has returned with error). So how is it works?
9/2/2016 10:48:45 AM
Max4 Answers
New AnswerHello, func backwards(s1: String, _ s2: String) -> Bool { return s1 > s2 }” sort function takes a function as an argument(backwards). The function do stuff(compare two strings here) and return a boolean value. That is the aim of closures: functions without names. When you pass true or false to the sort function as a parametre, sure you get an error. It is not about true or false but the decoration of the sort function: Sort(function that returns a boolean value). Enjoy.
Sololearn Inc.
535 Mission Street, Suite 1591Send us a message