Remove certain object from Array of Objects swift [duplicate] - ios

This question already has answers here:
Removing object from array in Swift 3
(13 answers)
Closed 2 years ago.
I have array of objects
let storeArray = [obj1, obj2, obj3]
And I want to remove obj2, how can I remove this with Swift 5?

If you specifically want to remove obj2, you can do this...
var storeArray = [obj1, obj2, obj3]
storeArray.removeAll(where: { $0 == obj2 })

If you know that obj2 is in index 1 of the array and you trust that:
var array = [obj1, obj2, obj3]
guard array.count > 1 else { return }
array.remove(at: 1)
If you want to remove the obj2 without trusting it's index:
var array = [obj1, obj2, obj3]
array.removeAll(where: { $0 == obj2 })

You can try this,
var storeArray = [obj1, obj2, obj3]
storeArray.remove(at: 1)
print(storeArray)

Related

How do I compare two array Objects - Swift 4

I have 2 Array of type [Any] - objects of dictionaries
And other array contains other set of objects [Any] (2nd array objects are contains in first array)
I need to find the index of the first array of second array elements
eg: -
let firstArray = [["key1":6],["key2":8],["key3":64],["key4":68],["key5":26],["key6":76]]
let secondArray = [["key3":64],["key6":68]]
How can I find the firstArray index of secondArray elements
let index = firstArray.index{$0 == secondArray[0]};
print("this value ", index);
will print optional(2) , it is basically 2
First, you take the keys from your secondArray. Then, you try to find the index of key in your firstArray. Be aware that some values might be nil if the key doesn't exist.
let firstArray = [["key1":6],["key2":8],["key3":64],["key4":68],["key5":26],["key6":76]]
let secondArray = [["key3":64],["key6":68], ["key8": 100]]
let indexes = secondArray
.map({ $0.first?.key }) //map the values to the keys
.map({ secondKey -> Int? in
return firstArray.index(where:
{ $0.first?.key == secondKey } //compare the key from your secondArray to the ones in firstArray
)
})
print(indexes) //[Optional(2), Optional(5), nil]
I also added an example case where the result is nil.

'didSet' certain elements inside Arrays - Swift [duplicate]

This question already has an answer here:
Swift didSet get index of array
(1 answer)
Closed 5 years ago.
I have an array, with multiple values. I want to detect if one of those values is changed, something like this:
var array =
[
1,
2,
3,
4 { didSet{ print("Value Changed")}},
5,
6
]
Is that possible, in any way?
Thanks
Swift 3.0
You can do like below to Observer which index of array is changed.
var oldArray: [Int] = []
var array = [ 1,2,3,4,5,6] {
willSet {
// Set old array value for compare
oldArray = array
}
didSet {
let changedIndex = zip(array, oldArray).map{$0 != $1}.enumerated().filter{$1}.map{$0.0}
print("index: \(changedIndex)")
}
}
// Now change value of index 4 of array
array[4] = 10 //index: [4]

How to remove item in Array? [duplicate]

This question already has answers here:
RemoveAtIndex crash from swift array
(5 answers)
Closed 6 years ago.
I am coding with Swift, and confuse with one problem.
I encountered Index out of Range Error when I am trying to remove one item from array during the array's enumeration.
Here is my error codes:
var array :[Int] = [0,1,2,3,4,5]
for (index, number) in array.enumerate() {
if array[index] == 2 {
array.removeAtIndex(index) // Fatal error: Index out of range
}
}
Does that means array.enumerate() not be called during each for loop?
I have to change my codes like that:
for number in array {
if number == 2 || number == 5 {
array.removeAtIndex(array.indexOf(number)!)
}
}
Or
var index = 0
repeat {
if array[index] == 2 || array[index] == 4 {
array.removeAtIndex(index)
}
index += 1
} while(index < array.count)
You are removing item at the same time when you are enumerating same array. Use filter instead:
var array: [Int] = [0,1,2,3,4,5]
array = array.filter{$0 != 2}
or, for multiple values, use Set:
let unwantedValues: Set<Int> = [2, 4, 5]
array = array.filter{!unwantedValues.contains($0)}
Same in one line:
array = array.filter{!Set([2, 4, 5]).contains($0)}

swift , sort nsmutableArray with objects [duplicate]

This question already has an answer here:
Sorting an array with instances of a custom class
(1 answer)
Closed 7 years ago.
i have nsmutablearray with objects
user_id , username , user_Last_Update_Info
and i want to sort this array by user_Last_Update_Info
how to do it ??
Try this:
arrayToSort.sortUsingComparator{
(obj1:AnyObject!, obj2:AnyObject!) -> NSComparisonResult in
var dateStr1 = obj1["user_Last_Update_Info"] as NSString
var date1: NSDate = dateFormatter.dateFromString(dateStr1)!
var dateStr2 = obj2["user_Last_Update_Info"] as NSString
var date2: NSDate = dateFormatter.dateFromString(dateStr2)!
return date2.compare(date1)
}
This should help:
// Example for Swift Array
myArray.sortInPlace {
obj1 , obj2 in
dic1.user_Last_Update_Info < dic2.user_Last_Update_Info
}
// Example for Swift NSMutableArray
// newArr is an optional [AnyObject], you should cast it to what you expect
let newArr = myArray.sortedArrayUsingDescriptors([NSSortDescriptor(key: "user_Last_Update_Info", ascending: true)])

Swift: Iterate through array and count Ints equal to 5

In Swift how would I iterate through the NSMutableArray of ints var numbers = [4,5,5,4,3] and count how many are equal to 5?
You can use reduce for this:
let array = [4,5,5,4,3]
let fives = array.reduce(0, combine: { $0 + Int($1 == 5) })
One possible solution:
numbers.filter {$0 == 5}.count

Resources