从 swift 中的数组中提取值
Extract vaues from an array in swift
我在对存储在数组中的对象的响应中获取字符串值。它正在存储 properly.Now 我想从我的数组中获取这些值,因为稍后我必须将它添加到另一个字符串中以获得它们的总和。我的数组看起来像这样 [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]
失败。
考虑到您声称数组应该保存值 [0.5,0.5,0.5]
,我认为是后一种情况。 [0.5,0.5,0.5]
是 Double
个值的数组,而不是 Int
个值。
尝试这样修复:
let array = defaults.array(forKey: "addonPrice") as? [Double] ?? [Double]()
更新
从评论来看,你似乎到处都在使用字符串,那么:
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([=12=])! }.reduce(0, +)
print(resultant)
let result = Double(itemprice!)! + resultant
print(result)
尽管我强烈建议您从一开始就使用Double
(存储和使用它)。
我在对存储在数组中的对象的响应中获取字符串值。它正在存储 properly.Now 我想从我的数组中获取这些值,因为稍后我必须将它添加到另一个字符串中以获得它们的总和。我的数组看起来像这样 [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]
失败。
考虑到您声称数组应该保存值 [0.5,0.5,0.5]
,我认为是后一种情况。 [0.5,0.5,0.5]
是 Double
个值的数组,而不是 Int
个值。
尝试这样修复:
let array = defaults.array(forKey: "addonPrice") as? [Double] ?? [Double]()
更新
从评论来看,你似乎到处都在使用字符串,那么:
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([=12=])! }.reduce(0, +)
print(resultant)
let result = Double(itemprice!)! + resultant
print(result)
尽管我强烈建议您从一开始就使用Double
(存储和使用它)。