简体   繁体   English

快速从数组中提取值

[英]Extract vaues from an array in swift

I'm getting values of string in my response to whom i'm storing in an array. 我在对存储在数组中的对象的响应中得到了字符串值。 Its is storing properly.Now i want to get that values out of my array because later i have to add that in an another string to get their sum. 它存储正确。现在我想从数组中获取该值,因为稍后我必须将其添加到另一个字符串中以获取它们的总和。 My array looks like this, [0.5,0.5,0.5]. 我的数组看起来像这样[0.5,0.5,0.5]。 I have to extract all the 0.5 values and add them. 我必须提取所有0.5值并将其添加。 I have tried a code it extract the values but in result it shows 0 value. 我试过了一个代码,它提取值,但结果显示0值。 My code is this, 我的代码是这样的

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)

i'm trying to add the arrays value to another value with the name itemprice. 我试图将数组值添加到另一个名为itemprice的值。 How can i get out all the values from my array and add them. 我如何从我的数组中取出所有值并添加它们。 The values in the array varies different time. 数组中的值在不同的时间变化。

You are getting 0 as a result of let resultant = array.reduce(0, +) because in 你得到0作为结果let resultant = array.reduce(0, +)因为在

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

either the value stored in the defaults is an empty array, or the cast as? [Int] 存储在默认值中的值是一个空数组还是强制转换as? [Int] as? [Int] fails. as? [Int]失败。

Considering you claim that the array is supposed to hold values [0.5,0.5,0.5] I assume that it is the latter case. 考虑到您声称该数组应该保存值[0.5,0.5,0.5]我认为是后一种情况。 [0.5,0.5,0.5] is an array of Double values, not Int values. [0.5,0.5,0.5]Double值而不是Int值的数组。

Try to fix it this way: 尝试通过以下方式修复它:

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

UPDATE UPDATE

From comments it seems that you are using strings everywhere, so then: 从注释看来,您似乎在各处使用字符串,因此:

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)

Although I would strongly recommend you to work with Double from the beginning (both to store it and use it). 尽管我强烈建议您从一开始就使用Double (既要存储它也要使用它)。

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

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