【问题标题】:Count elements of nested array swift快速计算嵌套数组的元素
【发布时间】:2021-02-19 20:52:32
【问题描述】:

这里有人知道如何计算 Swift 中所有嵌套的自定义对象数组中的元素数量吗?

即我有

[Comments] 数组,其中包括 [Attachments] 数组。每个可能有 100 个 cmets 和 5 个附件。计算所有 cmets 中所有附件的最快捷方式是什么?我尝试了一些解决方案,如 flatMap、map、compactMap、filter、reduce,但无法弄清楚如何达到期望的结果。唯一对我有用的是典型的 for in loop。

    for comment in comments {
        attachmentsCount += comment.attachments.count
    }

有没有更好的方法来达到同样的效果?谢谢

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您可以使用Arrayreduce(_:_:) 函数来做到这一点:

    let attachementsCount = comments.reduce(0) { $0 + $1.attachments.count }
    

    【讨论】:

      【解决方案2】:

      这里有两种基于使用map的方法

      首先是reduce

      let count = comments.map(\.attachments.count).reduce(0, +)
      

      还有一个使用joined的变体

      let count = comments.map(\.attachments).joined().count
      

      【讨论】:

      • 有趣的是,他知道每一个答案都是错误的……
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 2020-10-05
      • 1970-01-01
      相关资源
      最近更新 更多