Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active August 29, 2015 14:17
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 JadenGeller/12b6b38634f421302f13 to your computer and use it in GitHub Desktop.
Save JadenGeller/12b6b38634f421302f13 to your computer and use it in GitHub Desktop.
Swift Bind (Non-Optional Let Expression)
// Let's start with an example!
bind(view.frame.size) { size in
println("The area is \(size.width * size.height)")
}
// Without bind, this code would look like this
// let size = view.frame.size
// println("The area is \(size.width * size.height)")
// Note how bind cleans up code that accesses the same variable
// multiple times. Much nicer. It restricts the scope too,
// making this preferable to a seperate let binding.
// Ideally, swift would support
// let size = view.frame.size {
// println("The area is \(size.width * size.height)")
// }
// but since it doesn't, this is the best we get.
// Even cooler would be a construct like this
// bind view.fram.size {
// println("The area is \(.width * .height)")
// }
// but I doubt we will get support for anything like that.
// Also, that might conflict with enum syntax. #awk
// The implementation is actually really simple:
func bind<T>(value: T, action: T -> ()) {
action(value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment