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...
}

```
Here’s a quick and dirty implementation of Duncan C’s suggestion to use a `buttonIsSelected` variable to store the button state:

```
import UIKit

class ViewController: UIViewController {

  var buttonIsSelected = false
  @IBOutlet weak var onOffButton: UIButton!

  override func viewDidLoad() {
    super.viewDidLoad()
    updateOnOffButton()
  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }

  @IBAction func onOffButtonTapped(_ sender: Any) {
    buttonIsSelected = !buttonIsSelected
    updateOnOffButton()
  }

  func updateOnOffButton() {
    if buttonIsSelected {
      onOffButton.backgroundColor = UIColor.blue
    }
    else {
      onOffButton.backgroundColor = UIColor.white
    }
  }

}

```