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
list2Dimis a reference toMovie.list3, which is defined as[list1, list2]. Solist2Dim[0]gives us the exactlist1array we need.map(\.year)converts eachMovieinstance in the array to itsyearproperty, 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
mapstep by handling the year extraction directly within thereduceclosure—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
相关产品推荐
相关产品推荐

