nambatee
nambatee

Reputation: 1568

Combine two arrays and downcast elements

I have two arrays with 2 UIView elements each and I want to combine them into 1 array while downcasting the elements to UIImageView.

Is there a better way to do this than adding flapMapped arrays?

let topViews = [UIView(), UIView()]
let bottomViews = [UIView(), UIView()]

let imageViews = topViews.flatMap { $0 as? UIImageView } + bottomViews.flatMap { $0 as? UIImageView }

*My use case is putting arrangedSubviews of 2 different stack views in one array (in case topViews and bottomViews look stupid, it's just for simplicity).

Upvotes: 0

Views: 70

Answers (1)

Milan Nosáľ
Milan Nosáľ

Reputation: 19737

It's a nice solution and only slightly better way is, as @zgorawski mentioned,

let imageViews = (topViews + bottomViews).flatMap { $0 as? UIImageView }`

since now if you would want to add another array to the equation, you just have to add + anotherOne instead of + anotherOne.flatMap { $0 as? UIImageView }.

Upvotes: 1

Related Questions