[swift-users] FlatMap and Casting

Nate Birkholz nbirkholz at gmail.com
Thu Apr 21 14:53:06 CDT 2016

myView.layer.sublayers returns an array of CALayer objects. Some of my
sublayers are CAShapeLayers. I want to act on the CAShapeLayer objects.

Shouldn't flatMap allow me to conditionally cast CALayers to CAShapeLayers?

let layers = myView.layer.sublayers.flatMap({ $0 as? CAShapeLayer })

The compiler warns "Cast from '[CALayer]' to unrelated type 'CAShapeLayer'
always fails"

So it looks like $0 is the array itself.

This works:

let layers = myView.layer.sublayers?.filter({ $0 is CAShapeLayer }).map({
$0 as? CAShapeLayer })

But I thought FlatMap should do it in a single step.

Nate Birkholz
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160421/95678b33/attachment.html>

More information about the swift-users mailing list