gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:21:51 25 4
gpt4 key购买 nike

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

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

最佳答案

重载函数定义...

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

关于swift - 为什么带有可变参数的swift函数不能接收数组作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33118151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com