+ 3

I don't understand the backwards explanation of closure

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?

2nd Sep 2016, 10:48 AM
Max
4 ответов
+ 3
Use "sorted" instead of "sort" in swift 3
5th Sep 2016, 10:43 PM
Abdelkader Ait Assou
Abdelkader Ait Assou - avatar
+ 2
Hello, 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.
7th Sep 2016, 8:32 PM
Abdelkader Ait Assou
Abdelkader Ait Assou - avatar
0
still don't understand why boolean value turns to sorted reslut
24th Mar 2017, 11:26 AM
Xue Cao
Xue Cao - avatar
- 1
I dont know, sorry
4th Sep 2016, 6:31 AM
Ruchi Gupta
Ruchi Gupta - avatar