Skip to content

Instantly share code, notes, and snippets.

@JAStanton
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JAStanton/c720f18c6d8b2b83e3d3 to your computer and use it in GitHub Desktop.
Save JAStanton/c720f18c6d8b2b83e3d3 to your computer and use it in GitHub Desktop.
Swift Closures
// old fashion way to pass a sorting function
func backwards(s1: String, s2: String) -> Bool {
return s1 > s2
}
var reversed = sort(names, backwards)
// with closures, the {} denotes a function, everythig before 'in' keyword is function definition
reversed = sort(names, { (s1: String, s2: String) -> Bool in
return s1 > s2
})
// one lined
reversed = sort(names, { (s1: String, s2: String) -> Bool in return s1 > s2 } )
// infering types
reversed = sort(names, { s1, s2 in return s1 > s2 } )
// implicit returns
reversed = sort(names, { s1, s2 in s1 > s2 } )
// short hand arguments
reversed = sort(names, { $0 > $1 } )
// using the operator as a function
reversed = sort(names, >)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment