繁体   English   中英

快速从数组中提取值

[英]Extract vaues from an array in swift

我在对存储在数组中的对象的响应中得到了字符串值。 它存储正确。现在我想从数组中获取该值,因为稍后我必须将其添加到另一个字符串中以获取它们的总和。 我的数组看起来像这样[0.5,0.5,0.5]。 我必须提取所有0.5值并将其添加。 我试过了一个代码,它提取值,但结果显示0值。 我的代码是这样的

let itemprice = UserDefaults.standard.string(forKey: "itemPrice")
print(itemprice)
let defaults = UserDefaults.standard
let array = defaults.array(forKey: "addonPrice") as? [Int] ?? [Int]() 
print(array)
let resultant = array.reduce(0, +)
print(resultant)
let result = itemprice! + String(resultant)
print(result)

我试图将数组值添加到另一个名为itemprice的值。 我如何从我的数组中取出所有值并添加它们。 数组中的值在不同的时间变化。

你得到0作为结果let resultant = array.reduce(0, +)因为在

let array = defaults.array(forKey: "addonPrice") as? [Int] ?? [Int]() 

存储在默认值中的值是一个空数组还是强制转换as? [Int] as? [Int]失败。

考虑到您声称该数组应该保存值[0.5,0.5,0.5]我认为是后一种情况。 [0.5,0.5,0.5]Double值而不是Int值的数组。

尝试通过以下方式修复它:

let array = defaults.array(forKey: "addonPrice") as? [Double] ?? [Double]() 

UPDATE

从注释看来,您似乎在各处使用字符串,因此:

let itemprice = UserDefaults.standard.string(forKey: "itemPrice")
print(itemprice)
let defaults = UserDefaults.standard
// take it as an array of strings
let array = defaults.array(forKey: "addonPrice") as? [String] ?? [String]()
print(array)
// convert strings to Double
let resultant = array.map { Double($0)! }.reduce(0, +)
print(resultant)
let result = Double(itemprice!)! + resultant 
print(result)

尽管我强烈建议您从一开始就使用Double (既要存储它也要使用它)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM