3

Currently we have an array which contains all the contents of the JSON Object:

  var castArray: [CastData] = []

    CastData.updateAllData(urlExtension: "\(movieID)/credits", completionHandler: { results in

      guard let results = results else {
        print("There was an error retrieving upcoming movie data")
        return
      }
      self.castArray = results
})

I'm trying to split the results of the JSON object into 2 arrays, the first 5 will go into the first array, the remainder will go into the 2nd array:

var first5CastArrayObjects: [CastData]
var theRestofTheCastArrayObjects: [CastData] 

What would be the best way to do this?

SwiftyJD
  • 5,257
  • 7
  • 41
  • 92

1 Answers1

4
if castArray.count > 5 {
    let first5CastArrayObjects = castArray[0...4]
    var theRestofTheCastArrayObjects = castArray [5...castArray.count - 1]
} else {
    //Manage exception
}
Marco Santarossa
  • 4,058
  • 1
  • 29
  • 49
  • There should be a range check to ensure the array has at least 6 values or this code will crash. – rmaddy Feb 26 '17 at 22:11
  • as rmaddy has said, you need something like `if castArray.count >= 5 { do this code} else print("array too small") return` – mfaani Feb 26 '17 at 22:14
  • I tried this: if castArray.count >= 5 { let first5CastArrayObjects = castArray[0...4] self.first5CastArray.append(first5CastArrayObjects) } but it throw the error: Cannot convert value of type 'ArraySlice' to expected argument type 'CastData' – SwiftyJD Feb 26 '17 at 22:23
  • try self.first5CastArray += first5CastArrayObjects if you want to append the new array to an existing one – Marco Santarossa Feb 26 '17 at 22:26
  • @SwiftyJD check http://stackoverflow.com/a/35028887/5109911 – Marco Santarossa Feb 26 '17 at 22:28