Created
October 22, 2019 21:09
-
-
Save davbeck/230735d635db31b28ea26b80d72c73c2 to your computer and use it in GitHub Desktop.
Use if/else logic instead of a ternary operator in Swift. Don't do this.
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
func _if<T>(_ test: Bool, action: () -> T) -> T? { | |
if test { | |
return action() | |
} else { | |
return nil | |
} | |
} | |
extension Optional { | |
func _else(action: () -> Wrapped) -> Wrapped { | |
if let value = self { | |
return value | |
} else { | |
return action() | |
} | |
} | |
func _elseIf(_ test: Bool, action: () -> Wrapped) -> Wrapped? { | |
if let value = self { | |
return value | |
} else if test { | |
return action() | |
} else { | |
return nil | |
} | |
} | |
} | |
let something = true | |
let somethingElse = true | |
let value = _if(something) { | |
"A" | |
}._elseIf(somethingElse) { | |
"B" | |
}._else { | |
"C" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment