在for-in循环中使用尾随闭包 [英] Using trailing closure in for-in loop

查看:79
本文介绍了在for-in循环中使用尾随闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在for-in循环中使用数组的map()函数,如下所示:

I'm using map() function of array in for-in loop like this:

let numbers = [2, 4, 6, 8, 10]

for doubled in numbers.map { $0 * 2 } // compile error
{
    print(doubled)
}

会产生编译错误:

使用未解决的标识符"doubled"

Use of unresolved identifier 'doubled'

但是,如果我在map()函数中加上括号,则可以正常工作.即

However, if I put parenthesis for map() function, it works fine. i.e.

for doubled in numbers.map ({ $0 * 2 })
{
    print(doubled)
}

我的问题是,假设这是导致问题的原因,为什么编译器为什么不区分尾随函数和循环的代码块?

My question is, why wouldn't compiler differentiate code block of trailing function and loop, assuming this is causing the problem?

推荐答案

这是因为对于尾随函数应在其中运行的上下文存在歧义.一种可行的替代语法是:

This is because there would be ambiguity as to the context in which the trailing function should operate. An alternative syntax which works is:

let numbers = [2, 4, 6, 8, 10]

for doubled in (numbers.map { $0 * 2 }) // All good :)
{
    print(doubled)
}

我想说这可能是因为'in'运算符的优先级高于尾随函数.

I would say this is likely because the 'in' operator has a higher precedence than trailing functions.

取决于您,您认为它更具可读性.

It's up to you which you think is more readable.

这篇关于在for-in循环中使用尾随闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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