【问题标题】:Swift - sorting and reducing an array based on values of a second arraySwift - 根据第二个数组的值对数组进行排序和减少
【发布时间】:2018-10-20 21:54:17
【问题描述】:

我正在使用 NSFetchedResultsController 创建一个 tableView。在每个 tableViewCell 中都有一个金额,并且在每个部分标题中我想显示每个部分的总金额。例如,我从完整表格的核心数据中获取了一个双精度数组

array = [50.0, 1000.0, 100.0, 50.0]

还有一个包含每个部分的对象数量的第二个数组。

sum = [2, 1, 1]

我的问题是如何枚举第一个数组,然后通过第二个数组减少,因此部分总计的结果如下:

newArray = [1050.0, 100.0, 50.0]

也许通过使用 enumerateObjectsUsingBlock?

提前致谢!

【问题讨论】:

  • NSFetchedResultsController 通过其sectionNameKeyPath 属性(将针对每个对象进行评估的关键路径。将为此路径返回相同值的对象分组到同一节)。之后,遍历每个部分并为其项目生成总和将是微不足道的。
  • 您可以尝试使用@sum 等KVC 集合操作。在此处查看更多信息:stackoverflow.com/a/7572833/452767
  • @SergiySalyuk 这看起来很有希望。在我的 viewDidLoad 方法中,我正在使用 value(forKeyPath: "@sum.." 从我获取的项目中创建一个 NSNumber 数组但是我收到以下错误:this class is not key value coding-compliant for the key @sum.
  • @brookeemily 您可以在表格视图需要时立即生成节标题(例如,使用 titleForHeaderInSection)。因此,您获取给定部分的所有对象,然后对数组运行集合操作,只需确保使用正确的属性名称。

标签: arrays swift reduce enumerate


【解决方案1】:

这可能不是最有效的答案,但是,我认为它回答了您的问题

let array = [50.0, 1000.0, 100.0, 50.0]
let sum = [2, 1, 1]
var newArray = [Double]()

//Ensures that the amount of values you want to check in 'sum' doesn't
//exceed the amount of elements in 'array'
if sum.reduce(0, +) <= array.count {
    let val = sum[i]
    var total = 0.0

    for x in 0..<val {
        if x < array.count {
            total += array[index]
        }
        else {
            break
        }
        index += 1
    }
    newArray.append(total)
}
print(newArray)

【讨论】:

    【解决方案2】:

    在解决该问题后,我使用另一种技术找到了解决方案。如果有人感兴趣,我只需要将其添加到我的 viewForHeaderInSection 方法中:

    var totalArray = [Double]()    
    
    for i in 0...self.fetchedItemResultsController.sections![section].numberOfObjects-1 {
        let new = self.fetchedItemResultsController.sections![section].objects![i] as! Item
        totalArray.append(new.amount)
    }
    
    let amounts = totalArray.reduce(0, +)
    

    【讨论】:

      【解决方案3】:

      一个轻微的变体,使用切片。

      let array = [50.0, 1000.0, 100.0, 50.0]
      let numberInSections = [2, 1, 1]
      
      var sumOfSections : [Double] = []
      for _ in numberInSections { sumOfSections.append(0)}
      var firstIndex = 0
      
      for index in 0..<numberInSections.count {
        let lastIndex = firstIndex+numberInSections[index]
        if lastIndex > array.count { break }
        let sliceSum = array[firstIndex..<lastIndex].reduce(0, +)
        sumOfSections[index] = sliceSum
        firstIndex += numberInSections[index]
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-11-19
        • 2013-04-30
        • 2018-11-18
        • 2022-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多