Search code examples
iosarraysswiftinsert-updateitems

How to update all items in Array in the correct way


Have array of currency rates and after input amount in inputTextField i'm want to update all items in this array on the amount in this currency and put that one in the tableView, tried to do that with loop but that's not working correct because that's solution just putted in the table each loop

inputTextField that's name of the text field

receivedRates:[Double] = [1.1,1.6,2.0,1.3] // just example of the rates

for i in receivedRates {

    let newValue = Double(i)*Double(Int(inputTextField.text!)!)
    currentAmount.append(newValue)
    receivedRates = currentAmount
}

How to update this array without loop or maybe there some other solution for this loop?


Solution

  • You want to multply all items in the array with the double value of the text field.

    A very suitable way in Swift is map

    var receivedRates = [1.1, 1.6, 2.0, 1.3]
    
    receivedRates = receivedRates.map{ $0 * Double(inputTextField.text!)! }
    

    Alternatively you can enumerate the indices and update the values in place

    receivedRates.indices.forEach{ receivedRates[$0] *= Double(inputTextField.text!)! }
    

    I doubt that you really want to convert the text first to Int (losing the fractional part) and then to Double and of course you should unwrap the optionals safely.