Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the shortest way to run same code n times in Swift?

Tags:

swift

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?

like image 968
Evgenii Avatar asked May 31 '15 04:05

Evgenii


People also ask

How do you make a loop 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"]

How do you stop a loop in Swift?

You can exit a loop at any time using the break keyword.


2 Answers

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 
like image 165
Matteo Piombo Avatar answered Oct 11 '22 10:10

Matteo Piombo


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()     } } 
like image 31
ABakerSmith Avatar answered Oct 11 '22 10:10

ABakerSmith