bobcat
bobcat

Reputation: 177

Need help rewriting a bool as a ternary operator

I'm trying to write more ternary operators for if statements to practice, and I'm getting stuck on turning this into a ternary operator and need a bit of help.

I'm trying to animate the fade in and out of my status, navigation bar, toolbar, and a textslider.

I have:

var isHidden = false

@objc func textViewTapped(_ sender: UIGestureRecognizer) {  
    navigationController!.setNavigationBarHidden(!isHidden, animated: false)
    isHidden = navigationController!.isNavigationBarHidden

    UIView.animate(withDuration: 0.5, animations: {
        self.toolbar.isHidden = self.toolbar.isHidden ? false : true
        self.textSlider.isHidden = self.textSlider.isHidden ? false : true
        self.setNeedsStatusBarAppearanceUpdate()
    }, completion: nil)
}

As you can see, I got the toolbar and textSlider to work as a ternary operator. I need help converting this bit:

navigationController!.setNavigationBarHidden(!isHidden, animated: false)
    isHidden = navigationController!.isNavigationBarHidden

This is getting into views I can't see and I'm getting twisted up trying to convert it.

Upvotes: 0

Views: 1423

Answers (2)

JonJ
JonJ

Reputation: 1061

Swift 4.2 / Xcode 10 provides the Bool .toggle() function. Or you can roll your own for earlier versions:

extension Bool {

    mutating func toggle() {
        self = !self
    }

}

Just makes changing Bool values slightly more intuitive.

Upvotes: 0

Sweeper
Sweeper

Reputation: 271040

You don't need to use ternary operators here, just writing this would be enough:

UIView.animate(withDuration: 0.5, animations: {
    self.toolbar.isHidden = !self.toolbar.isHidden
    self.textSlider.isHidden = !self.textSlider.isHidden
    self.setNeedsStatusBarAppearanceUpdate()
}, completion: nil)

But I guess you are doing this to practice using the ternary operator, but please be aware that there are cases where the ternary operator is not useful at all. Not every if statement can be converted to one. e.g. this one:

if someCondition {
    someAction1()
    someAction2()
} else {
    someActon3()
    someAction4()
}

You can't write two statements as one of the operands of the ternary operator.

For the two lines in question, you can just follow the same logic you did with the above lines:

navigationController!.setNavigationBarHidden(isHidden ? false : true, animated: false)
isHidden = isHidden ? false : true // this is really redundant...

A more appropriate use case of the ternary operator is when you want to use different values of a non-Bool type depending on a condition. For example:

label.text = isHidden ? "I am hidden!" : "I am visible!"

Upvotes: 6

Related Questions