在这个文档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html / / apple_ref / doc / uid / TP40014097-CH2-XID_1
It mentions that when creating for
loops we can use the shorthand of 0..3
and 0...3
to replace i = 0; i < 3; ++i
and i = 0; i <= 3; ++i
respectively.
它提到,当创建for循环时,我们可以使用0的简写。3和0…3替换i = 0;我< 3;+i和i = 0;< = 3;+ +我分别。
All very nice.
都很好。
Further down the document in the Functions and Closures section it says that functions can have a variable number of arguments passed via an array.
在函数和闭包部分的文档后面,它说函数可以通过数组传递可变数量的参数。
However, in the code example we see the ...
again.
然而,在代码示例中,我们看到…一次。
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
Is this a mistake? It seems to me that a more intuitive syntax would be numbers: Int[]
.
这是一个错误吗?在我看来,更直观的语法应该是数字:Int[]。
A few examples down we see another code sample which has exactly that:
下面有几个例子,我们看到另一个代码示例,它有:
func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool {
2 个解决方案
#1
35
In case of all arguments are Int numbers: Int[] would be intuitive. But if you have code like this:
如果所有参数都是Int数:Int[]将是直观的。但是如果你有这样的代码:
func foo(args:AnyObject...) {
for arg: AnyObject in args {
println(arg)
}
}
foo(5, "bar", NSView())
output:
输出:
5
bar
<NSView: 0x7fc5c1f0b450>
#2
5
The type of parameter in sumOf are known as 'variadic' parameter. The parameters passed are accepted just as a group of elements and is then converted into array before using it within that function.
sumOf中的参数类型称为“可变参数”。传递的参数作为一组元素接受,然后在函数中使用之前转换为数组。
A great example would be this post.
这篇文章就是一个很好的例子。
Passing lists from one function to another in Swift
在Swift中从一个函数到另一个函数的列表。
#1
35
In case of all arguments are Int numbers: Int[] would be intuitive. But if you have code like this:
如果所有参数都是Int数:Int[]将是直观的。但是如果你有这样的代码:
func foo(args:AnyObject...) {
for arg: AnyObject in args {
println(arg)
}
}
foo(5, "bar", NSView())
output:
输出:
5
bar
<NSView: 0x7fc5c1f0b450>
#2
5
The type of parameter in sumOf are known as 'variadic' parameter. The parameters passed are accepted just as a group of elements and is then converted into array before using it within that function.
sumOf中的参数类型称为“可变参数”。传递的参数作为一组元素接受,然后在函数中使用之前转换为数组。
A great example would be this post.
这篇文章就是一个很好的例子。
Passing lists from one function to another in Swift
在Swift中从一个函数到另一个函数的列表。