Create a “forCount” control structure in Swift

风流意气都作罢 提交于 2019-12-10 12:55:23

问题


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.

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

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


Some similar concepts in Swift:

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

Using an ingenious extension to Int ...

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

回答1:


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

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.

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

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



回答2:


you can do

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

or

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


来源:https://stackoverflow.com/questions/32632438/create-a-forcount-control-structure-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!