2015-10-14 90 views
3

作爲標題,爲什麼swift可變參數不能接收數組作爲參數? 例如:爲什麼具有可變參數的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

比較[在Swift中將列表從一個函數傳遞給另一個函數](http://stackoverflow.com/questions/24008547/passing-lists-from-one-function-to-another-in-swift)。 –

回答

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

最後,我爲這個方法增加了一個這樣的過載: func test(ids:Int ...){ test(ids) } 看來我必須定義兩種方法來做到這一點。非常感謝你。 函數test(idArr:[Int]){ print(「\(idArr.count)rx as array」) – YonF

+0

是的,爲避免重複的代碼,您需要從可變參數調用Array版本。我會更新答案。 – Grimxn

1

可變參數接受零個或多個指定類型的值。

如果你想/需要有任何對象類型(數組,等等)在可變參數的參數,使用這個:

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