如何以正确的方式更新数组中的所有项目 [英] How to update all items in Array in the correct way

查看:152
本文介绍了如何以正确的方式更新数组中的所有项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有货币汇率的数组,并且在inputTextField中输入了金额后,我想更新此数组中该货币金额上的所有项目,然后将其放在tableView中,尝试通过循环来执行此操作,但不能正常工作因为那是每个循环都放在表中的解决方案

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是文本字段的名称

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?

推荐答案

您要使用文本字段的double值来填充数组中的所有项目.

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

在Swift中非常合适的方法是map

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!)! }

我怀疑您是否真的要先将文本转换为Int(丢失小数部分),然后再转换为Double,当然您应该安全地打开可选内容.

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.

这篇关于如何以正确的方式更新数组中的所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆