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 }
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()
}
}
you can do
let resultArr = (0..<n).map{$0+5}
or
(0..<n).forEach{print("Here\($0)")}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With