Skip to content

Instantly share code, notes, and snippets.

@SAllen0400
Last active January 1, 2017 04:13
Show Gist options
  • Save SAllen0400/93a051590f89f7684f87884f145e48f6 to your computer and use it in GitHub Desktop.
Save SAllen0400/93a051590f89f7684f87884f145e48f6 to your computer and use it in GitHub Desktop.
Basic Ternary Operator
// Bad way using if statement
func showMyView(bool: Bool) {
if bool == true {
UIView.animate(withDuration: 0.33, animations: {
self.myView.alpha = 1.0
})
} else {
UIView.animate(withDuration: 0.33, animations: {
self.myView.alpha = 0.0
})
}
// Better way using Ternary Operator
func showMyView(bool: Bool) {
UIView.animate(withDuration: 0.33, animations: {
self.myView.alpha = bool ? 1.0 : 0.0
})
}
// Another example of using a bool stated differently. Any bool result will do.
var isMyArrayEmpty = myArray.count == 0 ? true : false
// Another example of changing the way a button looks based on a bool.
func activateButton(bool: Bool) {
let image = bool ? onImage : offImage
let title = bool ? "Activated!" : "OFF"
let titleColor = bool ? UIColor.white : UIColor.yellow
let buttonColor = bool ? UIColor.red : UIColor.blue
setImage(image, for: .normal)
setTitle(title, for: .normal)
setTitleColor(titleColor, for: .normal)
backgroundColor = buttonColor
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment