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.
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() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With