在Swift中创建一个“forCount”控件结构

时间:2021-10-30 05:30:35

In many projects this control structure is ideal for readability:

在许多项目中,这种控制结构是可读性的理想选择:

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

You can do exactly that in objective-C.

你可以在Objective-C中做到这一点。

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

鉴于Swift对宏的方法与objective-c的方法截然不同,

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

有没有办法在Swift项目中创建这样的forCount(40)控件结构?


Some similar concepts in Swift:

Swift中的一些类似概念:

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

Using an ingenious extension to Int ...

使用Int的巧妙扩展...

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

2 个解决方案

#1


12  

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

Swift中没有预处理器宏,但您可以定义一个以迭代计数和闭包为参数的全局函数:

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("*")
}

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.

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

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

从Swift 3开始,“noescape”是函数参数的默认属性:

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

#2


1  

you can do

你可以做

let resultArr = (0..<n).map{$0+5}

or

要么

(0..<n).forEach{print("Here\($0)")}

#1


12  

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

Swift中没有预处理器宏,但您可以定义一个以迭代计数和闭包为参数的全局函数:

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("*")
}

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.

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

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

从Swift 3开始,“noescape”是函数参数的默认属性:

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

#2


1  

you can do

你可以做

let resultArr = (0..<n).map{$0+5}

or

要么

(0..<n).forEach{print("Here\($0)")}