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 it is a lot of typing.
for i in 0..<n { /* do something */ }
Is there a shorter/nicer way for running same code n
times in Swift?
You use the for - in loop to iterate over a sequence, such as items in an array, ranges of numbers, or characters in a string. This example uses a for - in loop to iterate over the items in an array: let names = ["Anna", "Alex", "Brian", "Jack"]
You can exit a loop at any time using the break keyword.
Speaking of syntax, you might define your own shortest syntax:
extension Int { func times(_ f: () -> ()) { if self > 0 { for _ in 0..<self { f() } } } func times(_ f: @autoclosure () -> ()) { if self > 0 { for _ in 0..<self { f() } } } } var s = "a" 3.times { s.append(Character("b")) } s // "abbb" var d = 3.0 5.times(d += 1.0) d // 8.0
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() } }
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