Here is one of my favorite extension I created for Array. Very useful shortcut when you use abstraction ( as you should ) and you want to create an array from another one.
Description
Instantiate an Array of type A with an another array of type ( or protocol ) B and fills it with elements from B that can be cast to A.
Code
1 2 3 4 5 6 7 8 9 |
init<T>(_ array:[T]) { self.init() for element in array { if let cast_element = element as? Element { self.append(cast_element) } } } |
Example
You could always use .filter but it would take way more lines. I often use it to get a specific subview in my view hierarchy. Here’s the link to the playground file.
MABDev.ArrayExtension.playground
That’s it for today folks ! See you soon. MAB.