创建一个"forCount" Swift中的控制结构 [英] Create a "forCount" control structure in Swift

查看:78
本文介绍了创建一个"forCount" Swift中的控制结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在许多项目中,此控制结构对于提高可读性非常理想:

In many projects this control structure is ideal for readability:

forCount( 40 )
 {
 // this block is run 40 times
 }

您可以在Objective-C中完全做到 .

You can do exactly that in objective-C.

鉴于Swift的宏方法与Objective-c的实现非常不同

Given that Swift has a very different approach to macros than objective-c,

是否可以在Swift项目中创建这样的forCount(40)控件结构?

is there a way to create such a forCount(40) control structure in Swift projects?

Swift中的一些相似概念:

Some similar concepts in Swift:

for _ in 1...40
 { // this block is run 40 times }

使用 Int的重要扩展 ...

40.times
 { // this block is run 40 times }

推荐答案

在Swift中没有预处理器宏,但是您可以使用迭代计数和闭包作为参数来定义全局 function :

There are no preprocessor macros in Swift, but you can define a global function taking the iteration count and a closure as arguments:

func forCount(count : Int, @noescape block : () -> ()) {
    for _ in 0 ..< count {
        block()
    }
}

使用尾随闭包语法",它看起来像内置 控制语句:

With the "trailing closure syntax", it looks like a built-in control statement:

forCount(40) {
    print("*")
}

@noescape属性允许编译进行一些优化 并在不使用self的情况下引用实例变量,请参见 Swift 1.2中的@noescape属性以获取更多信息.

The @noescape attribute allows the compile to make some optimizations and to refer to instance variables without using self, see @noescape attribute in Swift 1.2 for more information.

Swift 3起,"noescape"是该功能的默认属性 参数:

As of Swift 3, "noescape" is the default attribute for function parameters:

func forCount(_ count: Int, block: () -> ()) {
    for _ in 0 ..< count {
        block()
    }
}

这篇关于创建一个"forCount" Swift中的控制结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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