Jack Wu
Jack Wu

Reputation: 37

Object in array not being modified

I have this function that is supposed to find a "Buyer" object and modify the "amount" and "items" attribute of that buyer object.

Here is the code:

    func itemsToBuyers() {
        buyers = []
        for item in items! {
            for buyer in item.buyers {
                var result = buyers.filter({$0.name == buyer}).first
                if result == nil {
                    //add the buyer to the buyers array
                    let name: String = buyer
                    let amount: Float = Float(String(format: "%.2f", item.price/Float(item.buyers.count)))!
                    let items: [String] = [item.name]
                    let newBuyer = Buyer(expanded: false, name: name, amount: amount, items: items)
                    buyers.append(newBuyer)
                } else {
                    //update the amount and item list of buyer
                    print("adding")
                    result?.amount += Float(String(format: "%.2f", item.price/Float(item.buyers.count)))!
                    result?.items.append(item.name)
                }
            }
        }
    }

The initial insertion of each new Buyer object works fine, but the else statement is not behaving as expected. The code is being run and "adding is printed", but the object is not actually being modified.

Upvotes: 0

Views: 89

Answers (1)

HalR
HalR

Reputation: 11073

When you make this call

var result = buyers.filter({$0.name == buyer}).first

you are copying into result. When you change result later, it has no impact on the buyers array. These two lines change result, but not buyers:

result?.amount += Float(String(format: "%.2f", item.price/Float(item.buyers.count)))!
result?.items.append(item.name)

If buyer were not a value type, then you could be dealing with pointers instead of copied values and this approach could work.

Upvotes: 1

Related Questions