隐式转换函数接收元组 [英] Implicit cast function receiving tuple

查看:33
本文介绍了隐式转换函数接收元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现有一个隐式转换:
从采用 n 个参数的函数 (A, B, ...) ->R
函数采用 n 元组 ((A, B, ...)) ->R

I just found out there's an implicit cast :
From function taking n parameters (A, B, ...) -> R
To function taking a n-tuple ((A, B, ...)) -> R

示例 n°1

func withTuple(_ a: (Int, Int)) { }
func withoutTuple(_ a: Int, _ b: Int) { }

func call(tupleFunction: ((Int, Int)) -> ()) {
    tupleFunction((1, 2))
}

call(tupleFunction: withTuple)
call(tupleFunction: withoutTuple) // Magic here

(有效的 Swift 4.2 代码)

(Valid Swift 4.2 code)

示例 n°2

[(1, 2), (3, 3)].map(*) // Magic here

此行为是否记录在某处?

Is this behaviour documented somewhere?

推荐答案

在 Swift 3 之前,人们能够通过显式指定其参数或传递精心设计的元组来调用函数.然而,当 SE-0029 已实施.

Before Swift 3, one was able to call a function either by explicitly specifying its arguments, or by passing a well-crafted tuple. However this way of calling functions was removed when SE-0029 was implemented.

基本上,以下是可能的:

Basically, the following was possible:

func buildDescription(name: String, age: Int) -> String {
    return "Hi, I am \(name), and I am \(age)"
}

buildDescription("John Doe", age: 21)
// or, via a tuple, giving the same result
buildDescription(("John Doe", name: 21))

Swift 论坛有这个关于上述变化的帖子(强调我的):

The Swift forums have this post regarding the above change (emphasis mine):

该提案已被 Swift 3 接受.我们承认我们正在删除一个有用的功能,但没有提供同样具有表现力的替代品.但是,在类型检查器中保持这种行为是实现复杂性的一个严重来源,并且会积极干扰我们巩固类型系统的计划.

The proposal has been accepted for Swift 3. We acknowledge that we're removing a useful feature without providing an equally expressive drop-in replacement. However, maintaining this behavior in the type checker is a severe source of implementation complexity, and actively interferes with our plans to solidify the type system.

所以看起来像call-function-by-tuple支持只在类型检查器级别被禁止,这意味着你不能直接将元组传递给函数,但是编译器的内部结构保持不变,允许间接传递元组,就像问题中的例子一样.

So it looks like the call-function-by-tuple support was prohibited only at the type checker level, meaning you cannot directly pass tuples to functions, however the internals of the compiler remained the same, which allow indirect passes of tuples, like in the examples from the question.

这篇关于隐式转换函数接收元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆