【问题标题】:why swift function with variadic parameters can not receive an array as argument为什么带有可变参数的swift函数不能接收数组作为参数
【发布时间】:2015-10-14 06:31:49
【问题描述】:

如题,为什么 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)

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

【问题讨论】:

标签: swift variadic-functions


【解决方案1】:

重载函数定义...

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...

【讨论】:

  • 最后,我为这个方法添加了一个重载,比如这个 func test(ids : Int...) { test(ids) } 看来我必须定义两个方法来做到这一点。非常感谢你。 func test(idArr : [Int]) { print("(idArr.count) rx as array") }
  • 是的,为了避免重复代码,您需要从可变参数中调用 Array 版本。我会更新答案。
【解决方案2】:

可变参数接受零个或多个指定类型的值。

如果您想/需要在该可变参数中包含任何对象类型(数组,等等),请使用:

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

【讨论】:

    猜你喜欢
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 2020-10-03
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    相关资源
    最近更新 更多