我很快就到这儿了。正在阅读关于weheartswift的关闭。有一节谈论尾随关闭。这里有三个问题:
代码:
function sum(from: Int, to: Int, f: (Int) -> (Int)) {
var sum = 0
for i in from...to {
sum += f(i)
}
return sum
}
sum(1, 10) {
$0
} // the sum of the first 10 numbers
sum(1, 10) {
$0 * $0
} // the sum of the first 10 squares
答案 0 :(得分:2)
这是您的工作代码:
func sum(from: Int, to: Int, f: (Int) -> (Int)) -> Int{
var sum = 0
for i in from...to {
sum += f(i)
}
return sum
}
sum(1, to: 10) {
$0
} // the sum of the first 10 numbers
sum(1, to: 10) {
$0 * $0
} // the sum of the first 10 squares
根据您的错误,它表示您声明的函数没有任何返回值,但最后返回Int
return sum
。因此,通过添加-> Int
来更改您的函数语法,如上面的代码所示,该函数将返回Int
并且它将正常工作。