I am really new to Swift and working on my first project (I have a bit of experience with Javascript and web development). I have run into trouble (going on 4 hours of trying different solutions).

I have an app where when a `UIButton` is pushed it logs a value to FireBase (ON). When it is pushed a second time it logs (OFF) to the database.

When I make the button change the `view.backgroundColor` and put if else tied to the colour it works.

But I can't for the life of me figure out how to build my if else based on the state of the button. I have now ended up trying to change the colour of the button itself and tie the if else to that. Which I know is a really messy improper way to go about it.

```
import UIKit
import Firebase
import FirebaseDatabase

class ViewController: UIViewController {
    @IBAction func OnOffButton(_ sender: UITapGestureRecognizer){
        if button.backgroundColor == UIColor.white {
        OnOff(state:"ON")
            OnOffButton.backgroundColor = UIColor.blue
        } else{
            OnOff(state:"OFF")
            OnOffButton.backgroundColor = UIColor.white
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        OnOff(state: "Off")
        OnOffButton.backgroundColor = UIColor.white
    }

```
['https://Stackoverflow.com/questions/42103738', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7532077/']
`UIButton` inherits from `UIControl` which has an `isSelected` property. Use this to track state. Typically you'll use `button.isSelected == true` to correspond to your on state, and `false` is your off state.

To toggle state you can use `button.isSelected = !button.isSelected`.

For your specific example:

```
// User pressed the button, so toggle the state:
button.isSelected = !button.isSelected

// Now do something with the new state
if button.isSelected {
    // button is on, so ...
} else {
    // button is off, so...
}

```
Par's solution should work. However, I would suggest a different approach.

In general it's not good design to store state in a view object. It's fragile, and doesn't follow the MVC design pattern, where view objects display and collect state information, not store it.

Instead I would create an instance variable in your view controller, buttonIsSelected. Toggle that when the button is tapped, and have it change the state of the button's selected property, the button's color, AND log the new state to FireBase.

If you store more complex state in your view controller it would be worth separating that out into a model object. It can be as simple as a struct that holds the different state values. That way you have a clear separation between your controller (view controller) and model.