没有花括号和参数标签的匿名函数? [英] Anonymous function with no curly braces and no argument labels?

查看:36
本文介绍了没有花括号和参数标签的匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在另一个问题上看到了一些代码,似乎用一些不寻常的语法创建了一个匿名函数(闭包表达式):

I saw some code on another question that seems to create an anonymous function (closure expression) with some unusual syntax:

let plus: (Int, Int) -> Int = (+)

我理解左边——它声明了一个 (Int, Int) 类型的常量 ->Int(一个接受两个整数并返回一个整数的函数).但是什么是(+)?它如何声明一个没有大括号的函数,当没有任何类型的参数标签时,它如何引用这两个参数?

I understand the left side—that it's declaring a constant of type (Int, Int) -> Int (a function that takes two Integers and returns an Integer). But what is (+)? How can it declare a function without curly brackets, and how does it refer to the two arguments when there are no argument labels of any kind?

该函数接受两个参数,将它们相加,并返回结果.如果我将 + 操作符替换为不同的操作符(比如 *),操作就会改变.那么它是 {$0 + $1} 的某种简写吗?如果是这样,这个速记背后的逻辑是什么?

The function takes two arguments, adds them together, and returns the result. If I replace the + operator with a different one (say a *), the operation changes. So is it some kind of shorthand for {$0 + $1}? If so, what is the logic behind this shorthand?

推荐答案

实际上,这不是速记.

plus(Int, Int) -> 类型的变量整数.您可以将任何属于此类型(或其任何子类型)的对象分配给它.文字 lambda 闭包当然属于这种类型,但实际上命名函数或方法也可以.而这正是这里发生的事情.

plus is a variable of type (Int, Int) -> Int. You can assign it any object that is of this type (or any of its subtypes). A literal lambda closure is certainly of this type, but actually a named function or method would also do. And that is exactly what is happening here.

它正在将名为 + 的操作符方法对象分配给变量.

It is assigning the operator method object named + to the variable.

闭包中隐含地提到了这一点 语言指南章节:

This is mentioned sort-of implicitly in the Closures chapter of the language guide:

实际上还有一种更短的方式来编写上面的闭包表达式.Swift 的 String 类型将其大于运算符 (>) 的字符串特定实现定义为具有两个 String 类型参数的方法,并返回 Bool 类型的值.这与 sorted(by:) 方法所需的方法类型完全匹配.因此,您可以简单地传入大于号运算符,Swift 将推断您要使用其特定于字符串的实现:

Operator Methods

There’s actually an even shorter way to write the closure expression above. Swift’s String type defines its string-specific implementation of the greater-than operator (>) as a method that has two parameters of type String, and returns a value of type Bool. This exactly matches the method type needed by the sorted(by:) method. Therefore, you can simply pass in the greater-than operator, and Swift will infer that you want to use its string-specific implementation:

reversedNames = names.sorted(by: >)

所以,代码所做的是将Operator Method + 分配给变量plus.+ 只是分配给变量的函数名称.不涉及魔法速记.

So, what the code is doing is assigning the Operator Method + to the variable plus. + is simply the name of the function assigned to the variable. No magic shorthand involved.

看到这个你会惊讶吗?

let plus: (Int, Int) -> Int = foo

这篇关于没有花括号和参数标签的匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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