为什么速记参数名称 $0 返回所有参数的元组? [英] Why is the shorthand argument name $0 returning a tuple of all parameters?

查看:25
本文介绍了为什么速记参数名称 $0 返回所有参数的元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图定义一个可以容纳闭包的变量,但在使用 Swift 的速记参数名称时遇到了一些困难.获取以下代码片段:

I was trying to define a variable that can hold a closure and ran into some difficulties using Swift's shorthand argument names. Take the following code snippet:

var returnAString: (String, String) -> String
returnAString = { return $0 }

这给了我编译错误 '(String, String)' is not convertible to 'String'.当我修改闭包返回一个带有第一个参数值的字符串时,我会在一个元组中返回两个参数值.

This gives me the compile error '(String, String)' is not convertible to 'String'. When I modify the closure return a string with the first argument value, I get back both argument values in a tuple.

println(returnAString("1", "2")) // Prints "(1, 2)"

但是,如果我修改闭包以打印第二个参数,则会按预期打印正确的参数.

However, if I modify the closure to print the second argument the correct argument is printed as expected.

returnAString = { $1 }
println(returnAString("1", "2")) // Prints "2"

我觉得我在这里做的事情有点傻,但我找不到任何解释为什么会发生这种情况.

I've got the feeling that I'm doing something a little silly here, but I couldn't find any explanation of why this would be happening.

推荐答案

闭包 § 简写参数名称

…速记参数名称的数量和类型将从预期的函数类型中推断出来.

Shorthand Argument Names

… the number and type of the shorthand argument names will be inferred from the expected function type.

看起来这是预期的行为.通过仅提供 $0,您可以推断(至少对系统而言)您想要一个元组.

It looks like this is the expected behavior. By providing only $0 you are inferring (at least to the system) that you want a tuple.

这似乎只是使用 $0 的特例.例如,以下内容无法编译.

This only seems to be a special case of using $0. For example, the following cannot be compiled.

var returnAString3: (String, String, String) -> String
returnAString3 = { return $1 }

无论怎么修改.

returnAString3 = { return $1.0 } // still fails.

这篇关于为什么速记参数名称 $0 返回所有参数的元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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