[swift-users] FlatMap and Casting

Dennis Weissmann dennis at dennisweissmann.me
Thu Apr 21 15:49:29 CDT 2016


Since sublayers are optional you’re calling the the flatMap function on Optionals, which behaves differently.

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

should fix the problem :)

- Dennis

> On Apr 21, 2016, at 9:53 PM, Nate Birkholz via swift-users <swift-users at swift.org> wrote:
> 
> 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? i.e. 
> 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
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


More information about the swift-users mailing list