UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Closures | How they work?

Forums > 100 Days of SwiftUI

Can someone explain me how Closures will work. When you call your custom function like here backwards what will Swift do? I don´t get it how it will take your array and put all of it in s1 and s2. How does it know what should go in s1 and what in s2? This is the step ich can´t unterstand but I have to because without it I can´t write useful Swift code with oder conditions.

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]

func backward(_ s1: String, _ s2: String) -> Bool {
    return s1 > s2
}
var reversedNames = names.sorted(by: backward)
// reversedNames is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"]

Thank you for your help!

3      

If you look at the declaration for sorted(by:), you will see this:

func sorted(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> [Element]

So what this tells us is that the closure the compiler is expecting you to pass takes two parameters of whatever type the elements of your array are and returns a boolean indicating if they are ordered so that the second element is "higher" (whatever that means for the particular type) than the first element.

Swift will call this closure with the elements of the array, passing them in pairs until they are sorted. You can observe what happens by changing your backward function to this:

func backward(_ s1: String, _ s2: String) -> Bool {
    print([s1, s2])
    return s1 > s2
}

4      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.