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?

0

1 Answer 1

4
if castArray.count > 5 {
    let first5CastArrayObjects = castArray[0...4]
    var theRestofTheCastArrayObjects = castArray [5...castArray.count - 1]
} else {
    //Manage exception
}
Sign up to request clarification or add additional context in comments.

5 Comments

There should be a range check to ensure the array has at least 6 values or this code will crash.
as rmaddy has said, you need something like if castArray.count >= 5 { do this code} else print("array too small") return
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<CastData>' to expected argument type 'CastData'
try self.first5CastArray += first5CastArrayObjects if you want to append the new array to an existing one

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.