为什么带有可变参数的 swift 函数不能接收数组作为参数

why swift function with variadic parameters can not receive an array as argument

如题,为什么swift可变参数不能接收数组作为参数? 例如:

func test(ids : Int...){
    //do something
}
//call function test like this failed
test([1,3])
//it can only receive argument like this
test(1,3)

有时,我只能获取数组数据,我也需要函数可以接收可变参数,但不能接收数组参数。也许我应该定义两个函数,一个接收数组参数,另一个接收可变参数,除了这个还有其他解决方案吗?

A variadic parameter accepts zero or more values of a specified type.

如果您want/need在该可变参数中有任何对象类型(数组,无论什么),请使用:

func test(ids: AnyObject...) {
    // Do something 
}

重载函数定义...

func test(ids : Int...) {
    print("\(ids.count) rx as variadic")
}
func test(idArr : [Int]) {
    print("\(idArr.count) rx as array")
}
//call function test like this now succeeds
test([1,3])
//... as does this
test(1,3)

// Output:
// "2 rx as array"    
// "2 rx as variadic"

当然,为了避免重复代码,可变版本应该只调用数组版本:

func test(ids : Int...) {
    print("\(ids.count) rx as variadic")
    test(ids, directCall: false)
}
func test(idArr : [Int], directCall: Bool = true) {
    // Optional directCall allows us to know who called...
    if directCall {
        print("\(idArr.count) rx as array")
    }
    print("Do something useful...")
}

//call function test like this now succeeds
test([1,3])
//... as does this
test(1,3)

// Output:
// 2 rx as array
// Do something useful...
// 2 rx as variadic
// Do something useful...