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
3
-
1Possible duplicate of stackoverflow.com/questions/30035193/… or stackoverflow.com/questions/24395105/….Martin R– Martin R2015-10-24 16:19:37 +00:00Commented Oct 24, 2015 at 16:19
-
if you really need compile-time checked constant length arrays, I recommend looking into dependent types, this great article is just about what you want (there even is a Playground version of it :D)Kametrixom– Kametrixom2015-10-24 16:45:04 +00:00Commented Oct 24, 2015 at 16:45
-
@Kametrixom Thank you I will look into that! XDJimmy lemieux– Jimmy lemieux2015-10-25 15:13:49 +00:00Commented Oct 25, 2015 at 15:13
Add a comment
|
2 Answers
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)
1 Comment
Jimmy lemieux
Thank you! I realized this just after I posted the question
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
1 Comment
Kametrixom
You can't catch such an error in Swift.. Only functions which
throw can throw an error