加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift中的元组和函数参数

发布时间:2020-12-14 04:41:14 所属栏目:百科 来源:网络整理
导读:在 Swift中,元组与函数参数有什么关系? 在以下两个示例中,函数返回相同的类型,即使一个采用元组而另一个采用两个参数.从调用者的角度来看(没有窥视代码),函数是否采用元组或常规参数没有区别. 函数参数在某些方面与元组有关吗? 例如 func testFunctionUsin
在 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编译器如何将各种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口译员可以访问.]

从AirSpeedVelocity起

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.

当我们达到’我说土豆’时,请记住’哲学基调’;你说土豆’阶段.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读