在以下两个示例中,函数返回相同的类型,即使一个采用元组而另一个采用两个参数.从调用者的角度来看(没有窥视代码),函数是否采用元组或常规参数没有区别.
例如
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编译器如何将各种paren表单转换为内部表示形式:
() -> Void (x) -> x (x,...) -> [Tuple x ...]
而且,如果有一个元组?函数,它将返回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.
当我们达到’我说土豆’时,请记住’哲学基调’;你说土豆’阶段.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。