在 Swift 中,元组与函数参数有什么关系?
在下面的两个例子中,函数返回相同的类型,即使一个接受一个元组而另一个接受两个参数。从调用者的角度来看(不看代码),函数采用元组参数还是常规参数没有区别。
函数参数在某些方面与元组相关吗?
例如
func testFunctionUsingTuple()->(Int, String)->Void {
func t(x:(Int, String)) {
print("\(x.0) \(x.1)")
}
return t
}
func testFuncUsingArgs()->(Int, String)->Void {
func t(x:Int, y:String) {
print("\(x) \(y)")
}
return t
}
do {
var t = testFunctionUsingTuple()
t(1, "test")
}
do {
var t = testFuncUsingArgs()
t(1, "test")
}
在常规函数(而不是返回函数)的函数参数中声明元组时,行为也存在不一致:
func funcUsingTuple(x:(Int, String)) {
print("\(x.0) \(x.1)")
}
func funcUsingArgs(x:Int, _ y:String) {
print("\(x) \(y)")
}
// No longer works, need to call funcUsingTuple((1, "test")) instead
funcUsingTuple(1, "test")
funcUsingArgs(1, "test3")
更新:
Chris Lattner 对元组的解释:
"x.0” where x is a scalar value produces that scalar value, due to odd behavior involving excessive implicit conversions between scalars and tuples. This is a bug to be fixed.
In "let x = (y)”, x and y have the same type, because (x) is the syntax for a parenthesis (i.e., grouping) operator, not a tuple formation operator. There is no such thing as a single-element unlabeled tuple value.
In "(foo: 42)” - which is most commonly seen in argument lists - you’re producing a single element tuple with a label for the element. The compiler is currently trying hard to eliminate them and demote them to scalars, but does so inconsistently (which is also a bug). That said, single-element labeled tuples are a thing.
最佳答案
每个函数只接受一个包含函数参数的元组。这包括没有参数的函数,它们将 ()
- 空元组 - 作为其一个参数。
以下是 Swift 编译器如何将各种括号形式转换为内部表示的方式:
() -> Void
(x) -> x
(x, ...) -> [Tuple x ...]
而且,如果有一个 tuple?
函数,它会在以下情况下返回 true:Void
、X
、[Tuple x ...]
。
这是你的证明:
let t0 : () = ()
t0.0 // error
let t1 : (Int) = (100)
t1.0 -> 100
t1.1 // error
let t2 : (Int, Int) = (100, 200)
t2.0 -> 100
t2.1 -> 200
t2.2 // error
[大胆声明目前没有可用的 Swift 解释器。]
But wait, you ask, what if I pass something other than a tuple in? Well, I answer (in a deeply philosophical tone), what really is a variable if not a tuple of one element? Every variable in Swift is a 1-tuple. In fact, every non-tuple variable has a .0 property that is the value of that variable.4 Open up a playground and try it. So if you pass in a non-tuple variable into TupleCollectionView, it’s legit for it to act like a collection of one. If you’re unconvinced, read that justification again in the voice of someone who sounds really confident.
当我们谈到“我说土 bean ;你说土 bean 阶段。
关于swift - Swift 中的元组和函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31320714/