DEV Community

unbug
unbug

Posted on

3

Swift and JavaScript comparison snippets - Closures

GitHub: https://github.com/unbug/sj

Closures

Swift

// Closure Expressions
// The Sorted Method
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"]
reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
    return s1 > s2
})
// or
reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in return s1 > s2 } )

JavaScript

// Closure Expressions
// The Sort Method
const names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
function backward(s1, s2) {
    return s1 < s2
}
let reversedNames = names.sort(backward)
// reversedNames is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"]
reversedNames = names.sort((s1, s2) => {
    return s1 < s2
})
// or
reversedNames = names.sort((s1, s2) => return s1 < s2)

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay