我想在函数中使用数组 numbers
中的数字。我只想将 2 与 3 相乘、3 与 3 相乘、5 与 3 相乘以及 2 与 3 相乘。但是,我得到一个错误。我做错了什么?
import Foundation
let numbers = [2, 3, 5, 2];
func num(number: [Int]...) {
for item in number {
let result = item * 3
print (result)
}
}
num(numbers)
Binary operator '*' cannot be applied to operands of type '[Int]' and 'Int'
最佳答案
您正在将数组的数组传递给函数。 num()
的函数参数应该只是 [Int]
或 Int...
编辑
Int...
和 [Int]
的区别
使用 Int...
,您可以传递可变数量的参数而无需显式使用数组:
func num(mult: Int, arr: Int...){
for n in arr{
println("num = \(n * 3)")
}
}
num(1,2,3,4) // first param (1) == mult(iplier), rest are ints captured by arr
在使用数组 ([Int]
) 时,您必须显式传递一个数组:
func num(mult: Int, arr: [Int]){
for n in arr{
println("num = \(n * 3)")
}
}
num(1, [2,3,4]) // 1 == mult(iplier,), rest are the Ints to operate with
第二种解决方案显然更清洁。
我个人从未使用过Int...
,但它绝对有其用武之地...
不用说那些 (请参阅下面@Qbyte 的评论,了解此声明为何错误) Int...
参数需要放在参数列表的末尾...
关于swift - 函数的数组输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32429293/