I have a code that I need to run exactly n
times in Swift. What is the shortest possible syntax for that?
I am currently using the for
loop but
Sticking with a for
loop - you could extend Int
to conform to SequenceType
to be able to write:
for i in 5 { /* Repeated five times */ }
To make Int
conform to SequenceType
you'll could do the following:
extension Int : SequenceType {
public func generate() -> RangeGenerator<Int> {
return (0..<self).generate()
}
}
In Swift, what you have is the shortest syntax for performing a loop operation.
Swift provides two kinds of loop that perform a set of statements a certain number of times:
The for-in loop performs a set of statements for each item in a sequence.
The for loop performs a set of statements until a specific condition is met.
If you want to run it infinite times, well try using a while
.
ONLY 5 CHARACTERS (not including n or code)
r(){}
If you're just testing things and need a REALLY short line, try this. Emphasis on using this for testing, not in production, because no one will know what is going on without documentation.
define this somewhere globally
func r(_ n : UInt, _ c: @escaping () -> Void) { for _ in 0..<n { c() } }
call this when you want to run it
r(5) { /*code*/ }
You could do something like this:
10⨉{ print("loop") }
Using a custom operator and an extension on Int
:
infix operator ⨉ // multiplication sign, not lowercase 'x'
extension Int {
static func ⨉( count:Int, block: () ->Void ) {
(0..<count).forEach { _ in block() }
}
}
for _ in 1...5 {
//action will be taken 5 times.
}
you could use functional programming on a range instead of a loop, for shorter and "nicer" syntax for example
(0..<n).forEach{print("Index: \($0)")}
Other answers mention defining your own syntax for that. So - that can be fine for a tiny personal project, or as a learning experience. But defining your own syntax for something so trivial and basic in a large project would be maintenance and readability hell.