I don't understand the backwards explanation of closure | Sololearn: Learn to code for FREE!

+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?

9/2/2016 10:48:45 AM

Max

4 Answers

New Answer

+3

Use "sorted" instead of "sort" in swift 3

+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.

0

still don't understand why boolean value turns to sorted reslut

-1

I dont know, sorry