Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.