Converting NSArray to Swift Array <T> and filtering Elements not matching T

Converting NSArray

to Swift Array

type is T

easy if all elements already have a type T

already:

let arr1 : NSArray = [1,2,3]
let arr2 = arr1 as? Array<Int> // works

      

But now suppose non-uniform NSArray

with objects that don't match T

:

let arr1 : NSArray = [1,2,3,"a"]
let arr2 = arr1 as? Array<Int> // nil, as not all elements are of type Int

      

What I am trying to achieve is a downcast that filters out all non-matching items T

. So in the above case, I want to get Array<Int>

which contains only objects [1,2,3]

.

How do you do this elegantly?

+3


source to share


1 answer


Condensed:

let arr1 : NSArray = [1,2,3,"a"]
let arr2 = (arr1 as Array<AnyObject>).filter { $0 is Int } as! Array<Int>

      



Step by step:

let arr2 = arr1 as Array<AnyObject>  // convert NSArray to Array of AnyObject
let arr3 = arr2.filter { $0 is Int } // keep only objects that are of type Int
let arr4 = arr3 as! Array<Int>       // force cast to Array<Int>, as now you know that all objects are of that type 

      

+5


source







All Articles