重載函數定義...
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中將列表從一個函數傳遞給另一個函數](http://stackoverflow.com/questions/24008547/passing-lists-from-one-function-to-another-in-swift)。 –