[swift-users] FlatMap and Casting

Nate Birkholz nbirkholz at gmail.com
Thu Apr 21 15:52:20 CDT 2016


I would swear I had marked the optional initially with the same result, but
it works, so apparently I didn't!

On Thu, Apr 21, 2016 at 1:49 PM, Dennis Weissmann <dennis at dennisweissmann.me
> wrote:

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


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


More information about the swift-users mailing list