title: iOS Swift: Array index out of range when accessing last property
body: <p>I'm running into an strange error. I'm appending an item to an array, and then accessing that item through the .last property, but I randomly get an "fatal error: Array index out of range".</p>
  
  <p>Here is my code (which is inside a for loop):</p>
  
  <pre><code>var thisLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
  currentMarkers.append(GMSMarker(position: thisLocation))
  
  var calle = obj["calle"] as String
  var numero = obj["numero"] as String
  var colonia = obj["colonia"] as String
  var direccion = "\(calle) \(numero), \(colonia)"
  var horarioSemanal = obj["horario_lv"] as String
  var horarioSabatino = obj["horario_s"] as String
  var nombre = obj["sucursal"] as String
  
  currentMarkers.last?.icon = UIImage(named: tipo.lowercaseString)
  currentMarkers.last?.title = "\(tipo) - \(nombre)"
  currentMarkers.last?.appearAnimation = kGMSMarkerAnimationPop
  currentMarkers.last?.snippet = direccion
  </code></pre>
  
  <p>The error randomly shows in one of the last four lines.
  I have also tried accessing it by:</p>
  
  <pre><code>currentMarkers[currentMarkers.count-1].snippet = direccion
  </code></pre>
  
  <p>with no luck.</p>
  
  <p>This code is part of a function called fetchSucursales() which I call in the background like this: </p>
  
  <pre><code>let qualityOfServiceClass = Int(QOS_CLASS_BACKGROUND.value)
  let inverseQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
  dispatch_async(inverseQueue, {
  
      dispatch_async(dispatch_get_main_queue(), { () -&gt; Void in
          self.labelStatus.text = "Obteniendo marcadores..."
          self.activityIndicatorUpdateMarkers.startAnimating()
      })
  
      self.fetchSucursales()
  
      dispatch_async(dispatch_get_main_queue(), { () -&gt; Void in
          self.labelStatus.text = "\(self.currentMarkers.count) marcadores encontrados."
          self.activityIndicatorUpdateMarkers.stopAnimating()
      })
  
  })
  </code></pre>
  
  <p>If I run it in the main queue everything works fine everytime:</p>
  
  <pre><code>    labelStatus.text = "Obteniendo marcadores..."
      activityIndicatorUpdateMarkers.startAnimating()
      fetchNearbyPlaces()
      labelStatus.text = "\(currentMarkers.count) marcadores encontrados."
      activityIndicatorUpdateMarkers.stopAnimating()
  </code></pre>
  
  <p>It's just that my app freezes while fetching the markers if I do it like this.</p>
  
  <p>The fact of it being randomly and at different lines (and after a different number of loops each time) makes me think it has something to do with it running in the background.</p>
  
  <p>I'm using Xcode 6.1 (6A1052d).</p>
  
  <p>Hope you can help me and many thanks in advance!</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>Implementing Nate's answer, now the error has moved to another lines, here is the start of my function:</p>
  
  <pre><code>func fetchSucursales() {
  
  mapView.clear()
  currentMarkers.removeAll(keepCapacity: false)
  let fileManager = NSFileManager.defaultManager()
  let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(NSBundle.mainBundle().bundlePath)!
  while let element = enumerator.nextObject() as? String {
      if element.hasSuffix("json") {
  
          let path = NSBundle.mainBundle().pathForResource(element.stringByDeletingPathExtension, ofType: element.pathExtension)
          let jsonData = NSData(contentsOfFile: path!, options: .DataReadingMappedIfSafe , error: nil)
          var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
          var sucursales : NSArray = jsonResult["markers"] as NSArray
  
          sucursalLoop: for sucursal in sucursales {
              let obj = sucursal as NSDictionary
  
              var tipo = obj["tipo"] as String
              var latitude:CLLocationDegrees = obj["latitud"]!.doubleValue
              var longitude:CLLocationDegrees = obj["longitud"]!.doubleValue
              if contains(searchedTypes, tipo.lowercaseString) {
                  //if latitude &lt; mapRadius["norte"] &amp;&amp; latitude &gt; mapRadius["sur"] &amp;&amp; longitude &gt; mapRadius["este"] &amp;&amp; longitude &lt; mapRadius["oeste"] {
  
                  for var index:Int = 0; index &lt; currentMarkers.count; ++index {
                      if latitude == currentMarkers[index].position.latitude &amp;&amp; longitude == currentMarkers[index].position.longitude {
                          if tipo.lowercaseString == "cajero" {
                              continue sucursalLoop
                          }else {
  
                              if currentMarkers[index].title.rangeOfString("cajero") != nil {
                                  currentMarkers.removeAtIndex(index)
                              }
                              //append
                          }
                      }
                  }
  
                  //Append
                  var thisLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
                  let newMarker = GMSMarker(position: thisLocation)
                  var calle = obj["calle"] as String
                  //Rest of code posted before
  </code></pre>
  
  <p>Now the error shows in the if latitude == currentMarkers[index].position.latitude &amp;&amp; longitude == currentMarkers[index].position.longitude { line or in the if currentMarkers[index].title.rangeOfString("cajero") != nil { line.</p>
  
  <p>I've added a println("(currentMakers.count)") just after the start of the for loop and I'm seeing it kind of prints garbage. It prints a lot of 1, then 2, then 3, till 8, and then:</p>
  
  <pre><code>8
  8
  8
  8
  8
  10
  10
  10
  10
  1100
  
  1100
  
  1100
  
  1100
  
  1100
  
  1100
  
  10
  11
  11
  11
  11
  </code></pre>
  
  <p>At the moment of the error, index was 2 and currentMakers.count was 30.</p>