Pass immutable variable with inout

148 views Asked by At

I create an object in ContentView of a class and pass it to a function

@StateObject var portfolio = Portfolio()

...

///Cannot pass immutable value as inout argument: 'portfolio' is a get-only property
setCoin(portfolio: &portfolio, currencyList: currencyList, currency: currency, quantity: quantity)

...

func setCoin(portfolio:inout Portfolio, currencyList: [String : Int], currency: String, quantity: String){

    for coin in portfolio.coins{
        if coin.name == currency{
            //Cannot assign to property: 'coin' is a 'let' constant
            coin.quantity = Double(quantity)
            portfolio.portfolioList.append(coin)
        }
    }
}

portfolio.coins is an array of objects obtained from a JSON decoding. I am attempting to add a quantity variable that is user input to use in views.

1

There are 1 answers

2
vadian On

Portfolio is reference type. And inout is for value types.

Just pass the reference

func setCoin(portfolio: Portfolio, currencyList: [String : Int], currency: String, quantity: String){

Edit: To modify coins which is apparently a value type array you have to use enumerated() and modify the item in the array directly by index

for (index, coin) in portfolio.coins.enumerated() {
    if coin.name == currency {
        portfolio.coins[index].quantity = Double(quantity)
        portfolio.portfolioList.append(portfolio.coins[index])
    }
}

I highly recommend to move the last line in the loop - actually the entire logic - into the model