title: Swift - UISwitch to change background colour - only works once?
body: <p>Learning Swift from scratch. Why does my UISwitch code only work once when trying to change the UIVIew background colour? I've seen something about IBOutlet, but don't know how to add. Any help appreciated.</p>
  
  <p>Thanks</p>
  
  <pre><code>//
  //  ViewController.swift
  //  testChangeBackground
  //
  //  Created by Paul Balfour on 14/08/2014.
  //  Copyright (c) 2014. All rights reserved.
  //
  
  import UIKit
  
  class ViewController: UIViewController {
  
  var mySwitch = UISwitch()
  
  @IBAction func mySwitch(sender: UISwitch) {
  println("Switched")
      changeBackground()
  
  }
  
  func changeBackground() {
      if mySwitch.on {
          self.view.backgroundColor = UIColor.redColor()
          return
      }
      else
      {
          self.view.backgroundColor = UIColor.yellowColor()
          return
      }
  }
  
  
  override func viewDidLoad() {
      super.viewDidLoad()
      // Do any additional setup after loading the view, typically from a nib.
  }
  
  override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
      // Dispose of any resources that can be recreated.
  }
  </code></pre>
  
  <p>}</p>
  
  <hr>
  
  <p>Aha. So the UISwitch also needs to be an outlet to work. - What I don't understand is why an IBOutlet too? (working below). Thanks</p>
  
  <p>import UIKit</p>
  
  <pre><code>class ViewController: UIViewController {
  
  
  @IBAction func mySwitch(sender: UISwitch) {
  println("Switched")
      changeBackground()
  
  }
  
  @IBOutlet var mySwitch: UISwitch!
  
  
  func changeBackground() {
      if mySwitch.on {
          self.view.backgroundColor = UIColor.redColor()
          return
      }
      else
      {
          self.view.backgroundColor = UIColor.yellowColor()
          return
      }
  }
  </code></pre>
  
  <p>}</p>