title: Using a delay in for loop -- Swift
body: <p>Im trying to make a simple startup application to learn Swift. I am new to programming in general and I am in a little over my head. This bit of code is meant to highlight (change the background color) of a certain UIButton and then change it back. At first I added a delay of 0.5 seconds to each action but then I learned a IBAction only updates once at end of execution?. So I then added the delay to increment each time. The code works for the first 3 or 4 loops but then acts up and does not delay correctly. Please help, Thanks</p>
  
  <pre><code>func SSSays(clicks:Int) {
  
      sPattern.append(Int(arc4random_uniform(4) + 1))
      var wait = 0.5
  
  
      for button in sPattern {
  
          if(button == 1) {
              wait = wait + 0.5
              self.delay(wait) {self.BBB.backgroundColor = UIColor.init(red: (102/255), green: (178/255), blue: (255/255), alpha: (1))}
  
              wait = wait + 0.5
              self.delay(wait) { self.BBB.backgroundColor = UIColor.blueColor() }
  
  
          } else if(button == 2) {
  
              wait = wait + 0.5
              self.delay(wait) {self.RBB.backgroundColor = UIColor.init(red: (255/255), green: (153/255), blue: (153/255), alpha: (1))}
  
              wait = wait + 0.5
              self.delay(wait) {self.RBB.backgroundColor = UIColor.redColor() }
  
  
          } else if(button == 3){
  
              wait = wait + 0.5
              self.delay(wait) {self.GBB.backgroundColor = UIColor.init(red: (153/255), green: (255/255), blue: (204/255), alpha: (1)) }
  
              wait = wait + 0.5
              self.delay(wait) {self.GBB.backgroundColor = UIColor.greenColor() }
  
  
          } else if(button == 4){
  
              wait = wait + 0.5
              self.delay(wait) {self.OBB.backgroundColor = UIColor.init(red: (255/255), green: (204/255), blue: (255/255), alpha: (1)) }
              wait = wait + 0.5
              self.delay(wait) {self.OBB.backgroundColor = UIColor.magentaColor() }
  
          }
      }
  
  
  
  }
  
  
  
  
  func delay(delay:Double, closure:()-&gt;()) {
      dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(delay * Double(NSEC_PER_SEC))),dispatch_get_main_queue(), closure)
  }
  </code></pre>