Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a "forCount" control structure in Swift

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 }
like image 360
Fattie Avatar asked Sep 17 '15 14:09

Fattie


2 Answers

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()
    }
}
like image 188
Martin R Avatar answered Nov 04 '22 17:11

Martin R


you can do

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

or

(0..<n).forEach{print("Here\($0)")}
like image 38
GreatWiz Avatar answered Nov 04 '22 19:11

GreatWiz