Call a function multiple times and get a list of results in swift?

Viewed 527

I have a function func f() -> Int and I would like to call it n: Int times, and get the list of returned values.

In ruby, you would do n.times.collect { f }.

Does swift have a similar functional approach?

At the moment, I use the following handmade implementation:

extension Int {
  func collect<T>(f: () -> T) -> [T] {
    var l: [T] = []
    for _ in 0..<self {
      l.append(f())
    }
    return l
  }
}


// Usage
let myList = 42.collect { UIView(frame: self.bounds) }
1 Answers

This might not be the answer you're looking for, but you can use Ranges with higher order functions.

Example:

// a range of 1 to 42
let range = (1...42) 
let views1 = range.map { _ in
    return UIView(frame: self.bounds)
}


// Shorthand
let views2 = (1...42).map { _ in UIView(frame: self.bounds) }
Related