Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
677 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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() }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...