Swift - 根据第二个数组的值对数组进行排序和缩减

时间:2018-05-10 15:09:02

标签: arrays swift reduce enumerate

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

Heltidsulykke (-> Value should be "One") Fritidsulykke (-> value should be "Two") Børneulykke (-> value should be "Three")

和第二个数组,其中包含每个部分的对象数。

array = [50.0, 1000.0, 100.0, 50.0]

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

sum = [2, 1, 1]

也许使用enumerateObjectsUsingBlock?

提前致谢!

2 个答案:

答案 0 :(得分:0)

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

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)

答案 1 :(得分:0)

使用切片的轻微变体。

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]
}