David Sanford
David Sanford

Reputation: 745

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.

Upvotes: 0

Views: 290

Answers (3)

impression7vx
impression7vx

Reputation: 1873

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
    }
}

Upvotes: 1

vadian
vadian

Reputation: 285270

I recommend a for loop with a where clause as filter

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

Upvotes: 5

Sandeep Bhandari
Sandeep Bhandari

Reputation: 20379

Arguements passed to all the functions in swift are readonly (immutable in nature) unless the argument is marked with inout. So when you use filter $0 is immutable in nature so you cant simply set it to $0.isTemp = 0

what you can do is

        CurrentPolicyTemp.array = CurrentPolicyTemp.array.map({if $0.isTemp == 1 {
            var newPolicy = $0
            newPolicy.isTemp = 0
            return newPolicy
        }
        return $0 })

What am doing here is rather than trying to mutate the $0 I create a new copy of $0 and mutate it instead.

Upvotes: 1

Related Questions