多次调用一个函数并迅速获得结果列表?

时间:2019-06-21 09:23:59

标签: swift

我有一个函数func f() -> Int,我想调用它n: Int次,并获取返回值的列表。

在红宝石中,您会做n.times.collect { f }

迅速有类似的功能方法吗?

此刻,我使用以下手工实现:

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 个答案:

答案 0 :(得分:4)

这可能不是您要找的答案,但是您可以将function func(container, removing){ let result = container.filter(data => { if(removing.indexOf(data) < 0) return true;}) return result; // result = [1, 4, 5] } 与更高阶的功能一起使用。

示例:

Range