【问题标题】:Sum of values in a dictionary - Swift字典中的值总和 - Swift
【发布时间】:2016-09-18 00:44:53
【问题描述】:

所以这只是下面一些类似的示例代码。我试图把所有人的身高加在一起,这样我就可以得到一个平均值。我似乎无法弄清楚如何使用一系列字典来做到这一点。我也在使用 Xcode 3。

let people = [
    [
    "name": "John Doe",
    "sex": "Male",
    "height": "183.0"
    ],
    [
    "name": "Jane Doe",
    "sex": "Female",
    "height": "162.0"
    ],
    [
    "name": "Joe Doe",
    "sex": "Male",
    "height": "179.0"
    ],
    [
    "name": "Jill Doe",
    "sex": "Female",
    "height": "167.0"
    ],
]

下面的代码似乎只是创建了新的空数组。

var zero = 0.0
var peopleHeights = Double(player["height"]!)
var totalHeights = zero += peopleHeights!

下面的代码将每个单独的值加倍,所以不是我要找的。​​p>

var zero = 0.0
var peopleHeights = Double(player["height"]!)
var totalHeights = peopleHeights.map {$0 + $0}

在下面的代码中,我得到了响应:Double 类型的值没有成员减少。

var peopleHeights = Double(player["height"]!)
var totalHeights = peopleHeights.reduce(0.0,combine: +)

任何帮助将不胜感激。

【问题讨论】:

  • player 是一个数组,你希望player["height"] 做什么?

标签: arrays swift dictionary swift3


【解决方案1】:

您需要使用map 提取每个人的身高。然后你可以在包含高度的列表上应用reduce

您应该使用flatMap(Swift 4+ 上的compactMap)而不是map,因为+ 仅适用于未包装的值。

people.flatMap({ Double($0["height"]!) }).reduce(0, +)

斯威夫特 5

people.compactMap { Double($0["height"]!) }.reduce(0, +)

【讨论】:

  • 您不希望在 Swift 3 中使用 combine:。此外,您可能需要考虑使用 ?? "" 而不是 ! 来安全地展开高度字符串
  • 如何在swift 5中使用这个
【解决方案2】:

您也可以简单地遍历您的字典数组。

var totalHeight: Double = Double()

for person in people
{
    totalHeight += Double(person["height"]!)!
}

【讨论】:

  • 感谢您的帮助!
【解决方案3】:

compactMap 适合用于值的总和,因为它只考虑非零值。

let totalHeights = people.compactMap { $0["height"] as? Double}.reduce(0, +)

【讨论】:

    猜你喜欢
    • 2012-07-26
    • 2016-05-28
    • 2015-12-19
    • 1970-01-01
    • 2018-11-19
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多