数组输入功能

时间:2015-09-06 23:29:15

标签: swift function swift2

我想使用函数中数组numbers中的数字。我只想要3乘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)
  

二元运算符' *'不能应用于类型' [Int]'的操作数。和' Int'

4 个答案:

答案 0 :(得分:1)

删除...以便能够传递数组:

let numbers = [2, 3, 5, 2]

func num(number: [Int]) {
    for item in number {
        let result = item * 3
        print(result)
    }

}

num(numbers)

或者您可以直接使用vararg传递值:

func num(number: Int...) {
    for item in number {
        let result = item * 3
        print(result)
    }

}

num(2, 3, 5, 2)

答案 1 :(得分:1)

您正在将一个数组数组传递给该函数。 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评论为什么这个陈述是错误的)

答案 2 :(得分:1)

您正在传递IntArray<Array<Int>>)的数组数组。

Array<Int>[Int]Int...,但Int...参数值不能是[Int]的数组,它应该是{的序列{1}}秒。 例如。

Int

此外,您可以使用func foo(bar: Int...) { // bar is [Int] } foo(0, 3, 13, 6) // parameter is sequence of `Int`s 将变换应用于数组的每个元素。并且,使用.map()类型作为参数不是编写Swift代码的有效方法(您没有传递Int作为输入参数等),协议Array<UInt>为{{1}提供了函数运算符。所有默认的Swift整数类型都符合此协议。因此,这里唯一的方法是使用类型为IntegerArithmeticType的泛型函数,其中*。这是最终的代码:

T

PS:我使用了T: IntegerArithmeticType运算符,因为let numbers = [2, 3, 5, 2] /// Multilplies each element of array of `IntegerArithmeticTypes` by `multiplier`. /// /// - Parameter multiplier: `IntegerArithmeticTypes` multiplier for each element of array. /// - Parameter vals: Array of `IntegerArithmeticTypes` in which each element /// will be multiplied by `multiplier` /// /// - Returns: Array with multiplied values from `values` public func multipliedMap<T: IntegerArithmeticType>(multiplier: T, _ vals [T]) -> Array<T> { return vals.map { $0 &* multiplier } } dump(multipliedMap(3, numbers)) // prints: // // ▿ 4 elements // - [0]: 6 // - [1]: 9 // - [2]: 15 // - [3]: 6 值可能会溢出。

答案 3 :(得分:0)

试试这个:

 var numbers = [2, 3, 5, 2];

func num(number: [Int]) 
{
   var result = 0
    for var j  = 0; j < number.count - 1  ; j++
    {
        result = number[j] * number[j + 1]
        print ("\(result)")
     }
}

print(num(numbers))