Array Maximum Index Swift - ios

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

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)

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

Related

Add last element to an array from for loop

I have a code like so...
for element in self.arr_Offline {
self.arr_OfflineTemp.add(element)
break
}
self.arr_Offline.removeObject(at: 0)
Here I'm looping through an array called self.arr_Offline, adding the first element from that array into another array called self.arr_OfflineTemp and immediately doing break so that the second array will have just one element and then once I'm outside the for-loop, I remove the added object from the main array by doing self.arr_Offline.removeObject(at: 0)
But I want to add the last element to self.arr_OfflineTemp instead of the first and then remove that last element from self.arr_Offline. It should look something like so...
for element in self.arr_Offline { // looping through array
self.arr_OfflineTemp.add(lastElementOf'self.arr_Offline') //add last element
break
}
self.arr_Offline.removeObject(at: 'last') //remove that last element that was added to `arr_OfflineTemp`
How can I achieve this..?
First of all never use NS(Mutable)Array and NS(Mutable)Dictionary in Swift.
Native Swift Array has a convenient way to do that without a loop
First element:
if !arr_Offline.isEmpty { // the check is necessary to avoid a crash
let removedElement = self.arr_Offline.removeFirst()
self.arr_OfflineTemp.append(removedElement)
}
Last element:
if !arr_Offline.isEmpty {
let removedElement = self.arr_Offline.removeLast()
self.arr_OfflineTemp.append(removedElement)
}
And please drop the unswifty snake_case names in favor of camelCase
Did you try the same approach with reversed() Swift:
for i in arr.reversed():
// your code logic
After adding element, you can remove the last element from the list using this:
lst.popLast() or lst.removeLast()
Try this for the above code:
for element in self.arr_Offline.reversed() {
self.arr_OfflineTemp.add(element)
break
}
self.arr_Offline.popLast()
Is this something you are looking for?

How to append only few items into one array in Swift

Well, basically all im trying to do is I get a list of weather from the API which is an array of each node of the array represents a weather data every 3 hours, now all I want is to append only the first 6 items into my own array to load up the tableView with them.
so my question is : how can I append only six items into my own array? :)
since you have not posted any code, here is one example of how to do it.
var i = 0
for x in apiData{
if i >= 6 {
return
} else {
myArray.append(x)
i += 1
}
}
Note: this code will only append the first 6 items no matter what they are. If you want specific 6 items in the data the code will need to be modified, you will also need to provide more information in your question
Here is another way of doing so
if myArray.count == 6 {
return
}

index of out of range error based on selected button tag

I am currently attempting to select a player by passing the button tag property inside of an array as shown in this line of code below:
selectedPlayer = players[sender.tag]
When I compiled the application, it crashes and displays a index out of range error, which I figure is because I'm accessing passed the size of the array. I am aware that make sure that I don't exceed the bounds of the array I need to do something like this:
players.count - 1
Although I am not entirely sure how to implement the same idea with the previous line of code. Any suggestions?
You can use ternary operator ?::
selectedPlayer = (sender.tag < players.count) ? players[sender.tag] : nil
If you want to use one liner code.
You have an array players of N elements make sure that
0 <= buttonTag < N
so max value of the button tag should be = N - 1 , you can avoid the crash with
if sender.tag < players.count {
selectedPlayer = players[sender.tag]
}
but the above may not accomplish the needed functionality , you have to adhere to the rule above

(Swift) moving objects while iterating over array

I am trying to remove some objects from 1 array, and move them to another.
I am doing this by removing them from a reversed array, and adding them to another array, like so:
var array1 = [1,2,3,4,5,6]
var array2 = [1,2]
for (index, number) in array1.enumerated().reversed() {
if(number>2) {
array1.remove(at: index)
array2.append(number)
}
}
The problem is, the objects in array 2 are obviously reversed (1,2,6,5,4,3)
I can easily come up with complicated workarounds, but I was wondering if there are any straightforward ways of doing this.
Thanks in advance!
Rather than appending the numbers insert them
array2.insert(number, at: 2)
You can do the same thing without a loop
let droppedItems = array1.dropFirst(2)
array1.removeLast(array1.count - 2)
array2.append(contentsOf: droppedItems)
If I understand you correctly, you want to move numbers from array1 to array2 if they are higher than 2:
// get only numbers higher than 2 and append them to the second array
array2.append(contentsOf: array1.filter { $0 > 2 })
// filter the moved items from the first array
array1 = array1.filter { $0 <= 2 }
or
// split the array into two parts in place
let index = array1.partition { $0 > 2 }
// move the second part
array2 += array1[index...]
// remove the second part
array1.removeSubrange(index...)
Reverse it, grab subarray then append to array2. You don't need to mutate array1. Something like:
array2.append(contentsOf: array1.reversed()[0..<array1.count-1])

Object size limit in NSArray, NSData, NSMutuableArray?

In NSArray, NSMutuableArray,... data types, the addobject: method, can I
set the size of that to some limit?
Are you trying to constrain the amount of elements that can be added to an NSMutableArray?
if so, then you can just check that the current count is less then your desired max prior to adding a new object:
if (someMutableArray.count < max) {
[someMutableArray addObject:anObject];
};

Resources