高阶函数:"Cannot invoke 'map' with an argument list of type '((_) -> _)'"

Higher order function: "Cannot invoke 'map' with an argument list of type '((_) -> _)'"

我想使用 swift 高阶函数(映射)从给定的 UIView.subviews 数组中删除所有子视图。行

(cell.contentView.subviews as [UIView]).map { [=11=].removeFromSuperView() }

导致错误 "Cannot invoke 'map' with an argument list of type '((_) -> _)'"

我想知道此时编译器需要我做什么。

我会说地图不适合这种操作。它基于其他序列元素创建一个新序列,但您不想创建一个序列,您只想遍历它们并对它们应用一个函数。在 swift 中没有符合您要求的高阶函数,我希望他们能尽快添加一些东西。所以你能做的最好的就是使用 for 循环或编写你自己的函数来做你想做的事。

我想建议您编写自己的函数(基于 scalas foreach 是什么):

extension Array {

    func foreach(function: T -> ()) {
        for elem in self {
            function(elem)
        }
    }
}

更新为 Swift 2.0

forEach添加到SequenceType,所以可用:

(cell.contentView.subviews as [UIView]).forEach { [=11=].removeFromSuperview() }