Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialNOUR A ALGHAMDI
Courses Plus Student 5,607 Pointsplease i need an explain and help :\
good evening guys :) can some one explain to me , What is the benefit of writing this code :
let sortedNames = names.sort{(S1: String ,S2: String) -> Bool in return S1 > S2})
beside my code doesn't work :( can you help me how to fix it ?!
2 Answers
Jhoan Arango
14,575 PointsHello:
The benefit of writing this code, is that you can don't have to create a full function, and then pass it as the arguement to the sort() method. Meaning that you write less.. For example.
// Array of names
var names = ["Jhoan", "Harold","Carlos"]
// Function that sorts the names in order.
func sortNames(name1: String, name2: String) -> Bool {
return name1 < name2
}
// Passing the function as the argument for the sort() method.
let sortedNames = names.sort(sortNames)
// So instead of writing all this code, we can just use a closure, which is basically the same.
let sortedNames = names.sort { (S1: String, S2: String) -> Bool in return S1 < S2 }
Hope this helps you a bit
I recommend reading closures in this book
Aaron saunders
1,969 Points // you can even shrink the closure using
// Closure arguments can be references by position ($0, $1, ...) rather than by name
let sortedNames2 = names.sort { $0 < $1 }
print(sortedNames2)
Jhoan Arango
14,575 PointsThat is right.. but to make it even shorter, you can do this
let sortedNames = names.sort(>)
So, you write even less code.