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

拥有回忆 提交于 2019-11-27 07:02:51

问题


I would like to use a swift higher order function (map) to remove all Subviews from a given UIView.subviews array. The line

(cell.contentView.subviews as [UIView]).map { $0.removeFromSuperView() }

causes the error "Cannot invoke 'map' with an argument list of type '((_) -> _)'"

I would like to know what the compiler needs from me at this point.


回答1:


I would say that map is not for this kind of operation. It creates a new sequence based on an others sequences elements, but what you don't want to create a sequence, you just want to iterate through them and apply a function to them. In swift there is no higher order function that matches what you want, I hope they will put something in soon. So the best you can do is to use a for loop or write your own function which does what you want.

I would like to suggest to write your own functon (based on what scalas foreach is):

extension Array {

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

UPDATED with Swift 2.0

forEach added to the SequenceType, so it is available:

(cell.contentView.subviews as [UIView]).forEach { $0.removeFromSuperview() }


来源:https://stackoverflow.com/questions/28659616/higher-order-function-cannot-invoke-map-with-an-argument-list-of-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!