$ 0在Swift中的闭包中表示什么? [英] What does $0 represent in closures in Swift?

查看:136
本文介绍了$ 0在Swift中的闭包中表示什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到在swift的闭包里面有$ 0,有时他们使用$ 1。



这里是使用中的例子。

  applyMutliplication(2,{$ 0 * 3})
array.map({$ 0 + 1})

谢谢!

解决方案

这是一个简写参数名称。 >

从Swift Book:


Swift自动提供简写参数名称inline
闭包,可用于通过名称$ 0,$ 1,$ 2等引用闭包
参数的值。



- Apple Inc. Swift编程语言。


它有助于减少你的代码的冗长(有时以可读性为代价),所以你不必在定义闭包时写出长参数列表。


I have seen closures in swift have $0 inside of it and sometimes they use $1. What exactly is $0 and what are other $x can you use?

Here are examples of it in use.

applyMutliplication(2, {$0 * 3})
array.map({$0 + 1})

Thanks!

解决方案

It's a shorthand argument name.

From the Swift Book:

"Swift automatically provides shorthand argument names to inline closures, which can be used to refer to the values of the closure’s arguments by the names $0, $1, $2, and so on."

— Apple Inc. "The Swift Programming Language."

It helps reduce the verbosity of your code (sometimes at the cost of readability), so you don't have to write out long argument lists when defining closures.

这篇关于$ 0在Swift中的闭包中表示什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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