Swift3 使用reduce方法计算结构属性的总计
我想计算学生lis的总分,但我得到了这个错误。我的reduce方法实现有什么问题Swift3 使用reduce方法计算结构属性的总计,swift3,Swift3,我想计算学生lis的总分,但我得到了这个错误。我的reduce方法实现有什么问题 Cannot convert value of type '(_, _) -> Int' to expected argument type '(Result, Student) -> Result' 代码如下: import UIKit struct Student { let name: String var score: Int } var studentsList: [St
Cannot convert value of type '(_, _) -> Int' to expected argument type '(Result, Student) -> Result'
代码如下:
import UIKit
struct Student {
let name: String
var score: Int
}
var studentsList: [Student]
let totalScore = studentsList.reduce(0) {$0.score + $1.score}
应该是
let totalScore = studentsList.reduce(0) { $0 + $1.score }
不是
这里
(0)
是初始结果$0
是结果
在您的例子中,它是Int
,$1
是学生
类型。第一个学生首先初始化
var studentsList: [Student] = [] //or some list
它应该
let totalScore = studentsList.reduce(0) {$0.0 + $0.1.score}
反而
let totalScore = studentsList.reduce(0) {$0.score + $1.score}
$0
是累加器,它是Int
,没有分数
。
let totalScore = studentsList.reduce(0) {$0.score + $1.score}