2016-08-29 61 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

相关问题