Last active
October 1, 2015 10:14
-
-
Save tarunon/f7e97c19de1a14e4361d to your computer and use it in GitHub Desktop.
scala like "if" in swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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