You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何通过二维数组list2Dim计算list1内电影的年份总和

Solution

To calculate the sum of all year values from list1 without directly referencing it, we can leverage the fact that list2Dim points to Movie.list3—which contains list1 as its first element. Here's how to do it in Swift:

Option 1: Using map + reduce

// Extract the first array from list2Dim (which is list1), map to years, then sum
let totalYearSum = list2Dim[0].map(\.year).reduce(0, +)
print(totalYearSum) // Output: 11059 (1994+1972+2008+1974+2018+1993)

Option 2: Using reduce directly

// Sum years directly in the reduce closure without mapping first
let totalYearSum = list2Dim[0].reduce(0) { accumulator, movie in
    accumulator + movie.year
}
print(totalYearSum) // Same output: 11059

Explanation

  • list2Dim is a reference to Movie.list3, which is defined as [list1, list2]. So list2Dim[0] gives us the exact list1 array we need.
  • map(\.year) converts each Movie instance in the array to its year property, resulting in an array of integers.
  • reduce(0, +) takes that array of integers and sums them up, starting with an initial value of 0.
  • The second option skips the map step by handling the year extraction directly within the reduce closure—both approaches are valid, choose whichever you find more readable.

If you want to handle edge cases where list2Dim might not have a first element (though in your code it always will), you can use optional binding to be safe:

if let firstList = list2Dim.first {
    let totalYearSum = firstList.map(\.year).reduce(0, +)
    print(totalYearSum)
}

内容的提问来源于stack exchange,提问作者Wahib

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 21:02:35