Create a "forCount" control structure in Swift
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-incontrol statement:
forCount(40) { print("*")}
The @noescape
attribute allows the compile to make some optimizationsand 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 functionparameters:
func forCount(_ count: Int, block: () -> ()) { for _ in 0 ..< count { block() }}
you can do
let resultArr = (0..<n).map{$0+5}
or
(0..<n).forEach{print("Here\($0)")}