2016-08-29 63 views
2

什麼是...語法意味着功能參數Swift - 在函數參數中意味着什麼?

例如

func setupViews(views: UIView...) { 
    ... 
} 

我在一些教程看到這個最近而據我瞭解它只是UIViews的數組。

因此,它是一樣的書寫

func setupViews(views: [UIView]) { 
    ... 
} 

還是有區別嗎?

+2

打開https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html並向下滾動到「可變參數」。 – Moritz

回答

3

它代表一個可變參數Paramater,從docs

甲可變參數參數接受指定類型的零倍或更多的值。 使用可變參數指定參數可以是 當函數被調用時傳遞了不同數量的輸入值。 通過在參數的類型名稱後插入三個句點字符(...) 來寫可變參數。

傳遞給可變參數的值可在 函數的主體中作爲適當類型的數組使用。例如, 一個名稱爲數字並且類型爲Double... 的可變參數在函數的主體內可用作常量數組 ,該數組被稱爲[Double]類型的數字。

下面的例子計算任何長度的號碼的列表的算術平均值(也被稱爲平均 ):

func arithmeticMean(numbers: Double...) -> Double { 
    var total: Double = 0 
    for number in numbers { 
     total += number 
    } 
    return total/Double(numbers.count) 
} 
arithmeticMean(1, 2, 3, 4, 5) 
// returns 3.0, which is the arithmetic mean of these five numbers 
arithmeticMean(3, 8.25, 18.75) 
// returns 10.0, which is the arithmetic mean of these three numbers 

只能有每個功能一個可變參數帕拉姆。

正如你可以看到,存在當使用一個函數具有可變參數的參數則不需要傳遞的對象/值作爲陣列的[Double]輸入paramater和Double...

之間細微的差別。

思考的食物;你怎麼稱呼這個方法? func arithmeticMean(numbers: [Double]...) -> Double

像這樣:

arithmeticMean([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]) // you could keep adding more and more arrays here if desired. 

在這個例子中 '數字' 將雙數組的數組。

+1

非常感謝。在文檔中必須錯過這一部分。它不是我看到很多,所以我只是想知道它是什麼。 – crashoverride777

+0

@ crashoverride777,我的榮幸。 – Woodstock

+1

感謝您編輯您的答案,最後幾句幫助我正確理解它。我會在幾分鐘內記下它。 – crashoverride777

相關問題