Skip to content

Instantly share code, notes, and snippets.

@davbeck
Created October 22, 2019 21:09
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 davbeck/230735d635db31b28ea26b80d72c73c2 to your computer and use it in GitHub Desktop.
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.
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