Search code examples
iosarraysswiftnsarray

how to replace a single variable of multi element NSArray in Swift


I am struggling to update a single variable in an array create by Structs.

struct CurrentPolicyItems {
    var id:Int
    var currentInsured:String
    var currentPremium:String
    var currentXDate:String
    var typeID:Int
    var productID:Int
    var buildingID:Int
    var noteID:Int
    var isUsed:Int
    var isTemp:Int
}
struct CurrentPolicyTemp {
    static var array = [CurrentPolicyItems]()
}

When I close a class, I need to change all var "isTemp" from 1 to 0. Not all elements are used, so I need to filter them before any updates. I believe I am close, just can't get the last bit.

I have tried:

    if let items = CurrentPolicyTemp.array.firstIndex( where: { $0.isTemp == 1}) {
    CurrentPolicyTemp.array[items].isTemp = 0
    }

However, as we all know, this will only update a single element. I have tried .filter, but hit the error of "item is immutable" error.

Help please.


Solution

  • Array.firstIndex iterates through a loop to obtain the FIRST index that matches the following criteria. You simply take this a step back and do this yourself...

    for (index, item) in CurrentPolicyTemp.array.enumerated() where item.isTemp == 1 {
        CurrentPolicyTemp.array[index].isTemp = 0
    }
    

    Or on a simpler terms:

    for (index, item) in CurrentPolicyTemp.array.enumerated() {
        if(item.isTemp == 1) {
            CurrentPolicyTemp.array[index].isTemp = 0
        }
    }