gpt4 book ai didi

swift - 隐式转换函数接收元组

转载 作者:搜寻专家 更新时间:2023-10-31 22:53:27 24 4
gpt4 key购买 nike

我刚发现有一个隐式转换:
来自采用 n 个参数的函数 (A, B, ...) -> R
函数采用 n 元组 ((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 代码)

示例 n°2

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

是否在某处记录了此行为?

最佳答案

在 Swift 3 之前,人们可以通过显式指定参数或传递精心设计的元组来调用函数。然而,这种调用函数的方式在 SE-0029 时被删除了。已实现。

基本上,以下是可能的:

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 forums有关于上述更改的帖子(强调我的):

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.

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

关于swift - 隐式转换函数接收元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54283053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com