gpt4 book ai didi

swift - 函数的数组输入

转载 作者:搜寻专家 更新时间:2023-11-01 06:44:01 25 4
gpt4 key购买 nike

我想在函数中使用数组 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...,但它绝对有其用武之地... 不用说那些 Int... 参数需要放在参数列表的末尾... (请参阅下面@Qbyte 的评论,了解此声明为何错误)

关于swift - 函数的数组输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32429293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com