Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 936
Ula Avatar asked Jan 21 '18 09:01

Ula


2 Answers

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.

like image 102
vadian Avatar answered Nov 15 '22 04:11

vadian


You can also extend MutableCollection and implement your own mutable map method to transform your array:

extension MutableCollection {
    mutating func mutableMap(_ transform: (Element) throws -> Element) rethrows {
        var index = startIndex
        for element in self {
            self[index] = try transform(element)
            formIndex(after: &index)
        }
    }
}

Usage:

var receivedRates = [1.1, 1.6, 2.0, 1.3]
receivedRates.mutableMap { $0 * 2.5 }
print(receivedRates)    // [2.75, 4, 5, 3.25]

In your case:

if let value = Double(inputTextField.text!) {
    receivedRates.mutableMap { $0 * value }
}
like image 32
Leo Dabus Avatar answered Nov 15 '22 05:11

Leo Dabus