Skip to content

Instantly share code, notes, and snippets.

@k0nserv
Last active August 29, 2015 14:03
Show Gist options
  • Save k0nserv/b24f66cfac4c4b082793 to your computer and use it in GitHub Desktop.
Save k0nserv/b24f66cfac4c4b082793 to your computer and use it in GitHub Desktop.
Reimplementing the swift if statement without using the if keyword
func _if_without_if(condition: BooleanType, action: () -> ()) {
// We fake the false case by using an empty closure, e.g a NOP
let actions = [{}, action]
// boolValue returns a Bool and we can abuse the fact that
// hashValue of true is 1 and then hashValue of false is 0 to
// get the correct closure to run
actions[condition.boolValue.hashValue]()
}
_if_without_if(1 < 2) {
println("1 is less than 2 even without if")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment