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
Asked
Active
Viewed 225 times
0
-
1Possible duplicate of http://stackoverflow.com/questions/30035193/swift-create-a-fixed-length-array-enforced-at-compile-time or http://stackoverflow.com/questions/24395105/how-to-create-a-fixed-size-array-of-objects. – Martin R Oct 24 '15 at 16:19
-
if you really need compile-time checked constant length arrays, I recommend looking into dependent types, [this great article](https://bigonotetaking.wordpress.com/2015/09/04/in-which-i-misunderstand-dependent-types/) is just about what you want (there even is a Playground version of it :D) – Kametrixom Oct 24 '15 at 16:45
-
@Kametrixom Thank you I will look into that! XD – Jimmy lemieux Oct 25 '15 at 15:13
2 Answers
1
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)

Charles A.
- 10,685
- 1
- 42
- 39
0
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

Prem
- 157
- 7
-
1You can't catch such an error in Swift.. Only functions which `throw` can throw an error – Kametrixom Oct 24 '15 at 16:24