作为标题,为什么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)
有时,我只能获取数组数据,而且我还需要该函数可以接收可变参数,但不能接收数组参数。也许我应该定义两个函数,一个接收数组参数,另一个接收可变参数,除此之外还有其他解决方案吗?
答案 0 :(得分:3)
重载功能定义......
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...
答案 1 :(得分:1)
可变参数接受零个或多个指定类型的值。
如果您希望/需要在该可变参数中包含任何对象类型(数组,等等),请使用:
func test(ids: AnyObject...) {
// Do something
}