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

前端 未结 1 1298
失恋的感觉
失恋的感觉 2020-12-11 06:46

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 [UI         


        
相关标签:
1条回答
  • 2020-12-11 07:21

    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() }
    
    0 讨论(0)
提交回复
热议问题