swift - 函数的数组输入

标签 swift function swift2

我想在函数中使用数组 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/

相关文章:

function - 如何在Postman中设置全局功能?

ios - 必须调用父类(super class) 'UITableViewHeaderFooterView' 的指定初始化程序

iOS:使用 Swift2 删除 .DocumentDirectory 中的文件

ios - 其他 swift 标志中 "-D"的含义是什么

arrays - 比较 2 个数组并根据是否存在创建一个新数组,swift 5

ios - 如何通过单击 WKWebView 中的按钮打开社交链接

c - 在 C 中查找范围

ios - 如何在 Swift 函数中返回泛型参数的默认值?

ios - 如何使用另一个 View Controller 类的数组?

ios - sdk inside iOS framework swift