[英]Type 'Double' does not conform to protocol 'Sequence Type'
This is my code and I don't know why it's not working. 这是我的代码,我不知道为什么它不起作用。 The title is what the error says.
错误的标题就是标题。 I'm working with Swift in Xcode and the code is supposed to create a function with as many parameters as I tell it to have/unlimited.
我正在使用Xcode中的Swift,并且该代码应该创建一个函数,该函数具有我告诉它的拥有/不限数量的参数。
func addMyAccountBalances(balances : Double) -> Double {
var result : Double = 0
for balance in balances {
result += balance
}
}
the code is supposed to create a function with as many parameters as i tell it
该代码应该创建一个具有我告诉我的参数的函数
What you probably want is a function taking a variable number of arguments , this is indicated by ...
following the type: 你可能需要的是采取可变数量的参数的函数,这是由表示
...
以下类型:
func addMyAccountBalances(balances : Double ...) -> Double {
var result : Double = 0
for balance in balances {
result += balance
}
return result
}
print(addMyAccountBalances(1.0, 2.0, 3.0))
print(addMyAccountBalances(4.5, 5.6))
Inside the function, balances
has the array type [Double]
so that you can iterate over its elements. 在函数内部,
balances
的数组类型为[Double]
以便您可以迭代其元素。
Note that this can be written more compactly with reduce()
: 请注意,这可以使用
reduce()
紧凑地编写:
func addMyAccountBalances(balances : Double ...) -> Double {
let result = balances.reduce(0.0, combine: +)
return result
}
Your code does not compile because balances : Double
is just a double number, not an array or sequence. 您的代码无法编译,因为
balances : Double
只是一个双数,而不是数组或序列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.