Jimmy lemieux
Jimmy lemieux

Reputation: 439

Array Maximum Index Swift

Is there a way to set the maximum index size of an array. For example I have an array of UIImage but I only want the array to store 6 images. How would I set a restriction on that array so it can only hold 6 images

Upvotes: 0

Views: 234

Answers (2)

Prem
Prem

Reputation: 157

Initialize your array with size of 6 and then do any one of the following checks:

  • Check element count of the array before inserting new element
  • You can surround your insertion code with try / catch block with 'ArrayIndexOutOfBounds' Exception being handled

Upvotes: 0

Charles A.
Charles A.

Reputation: 11123

There is no such functionality. You would have to implement it yourself:

if array.count < 6 {
    array.append(element)
}

or perhaps:

while array.count >= 6 {
    array.removeFirst()
}
array.append(element)

Upvotes: 1

Related Questions