Skip to content

Instantly share code, notes, and snippets.

@tarunon
Last active October 1, 2015 10:14
Show Gist options
  • Save tarunon/f7e97c19de1a14e4361d to your computer and use it in GitHub Desktop.
Save tarunon/f7e97c19de1a14e4361d to your computer and use it in GitHub Desktop.
scala like "if" in swift
extension Optional {
func _else(state: () -> Wrapped) -> Wrapped {
return self ?? state()
}
func _else_if(@autoclosure condition: () -> Bool, state: () -> Wrapped) -> Wrapped? {
return self ?? _if(condition(), state: state)
}
}
func _if<R>(@autoclosure condition: () -> Bool, state: () -> R) -> R? {
if condition() {
return state()
}
return nil
}
func _if_let<A, R>(@autoclosure condition: () -> A?, _where: A -> Bool = { _ in true }, state: A -> R) -> R? {
if let a = condition() where _where(a) {
return state(a)
}
return nil
}
var a = _if(true) {
1
}
var b = _if(false) {
1
}._else {
2
}
var c: String?
var d = _if_let(c) { c in
c + "B"
}
c = "A"
var e = _if_let(c, _where: { c in c == "A" }) { c in
c + "B"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment