0

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.

4
  • 2
    How is Buyer declared? Commented Mar 24, 2020 at 20:56
  • 1
    Specifically, is it a struct or a class? Structs are value types Commented Mar 24, 2020 at 21:13
  • @PhillipMills, Buyer is a struct Commented Mar 24, 2020 at 21:54
  • I changed it from struct to class. This solved my problem. Thanks! Commented Mar 24, 2020 at 22:01

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I initially had the buyer object declared as a struct. I changed it to class, and that solved my problem. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.