将 NSArray 转换为 Swift Array<T> 并过滤掉不匹配 T 的元素
Convert NSArray to Swift Array<T> and filter out Elements not matching T
将 NSArray
转换为 T
类型的 Swift Array
很容易,如果所有元素确实已经是 T
类型的话:
let arr1 : NSArray = [1,2,3]
let arr2 = arr1 as? Array<Int> // works
但现在假设一个非同质 NSArray
对象不匹配 T
:
let arr1 : NSArray = [1,2,3,"a"]
let arr2 = arr1 as? Array<Int> // nil, as not all elements are of type Int
我试图实现的是过滤掉所有不匹配的元素的向下转换 T
。所以在上面的例子中,我想得到一个 Array<Int>
只包含对象 [1,2,3]
。
如何优雅地做到这一点?
压缩:
let arr1 : NSArray = [1,2,3,"a"]
let arr2 = (arr1 as Array<AnyObject>).filter { [=10=] is Int } as! Array<Int>
一步一步:
let arr2 = arr1 as Array<AnyObject> // convert NSArray to Array of AnyObject
let arr3 = arr2.filter { [=11=] 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
将 NSArray
转换为 T
类型的 Swift Array
很容易,如果所有元素确实已经是 T
类型的话:
let arr1 : NSArray = [1,2,3]
let arr2 = arr1 as? Array<Int> // works
但现在假设一个非同质 NSArray
对象不匹配 T
:
let arr1 : NSArray = [1,2,3,"a"]
let arr2 = arr1 as? Array<Int> // nil, as not all elements are of type Int
我试图实现的是过滤掉所有不匹配的元素的向下转换 T
。所以在上面的例子中,我想得到一个 Array<Int>
只包含对象 [1,2,3]
。
如何优雅地做到这一点?
压缩:
let arr1 : NSArray = [1,2,3,"a"]
let arr2 = (arr1 as Array<AnyObject>).filter { [=10=] is Int } as! Array<Int>
一步一步:
let arr2 = arr1 as Array<AnyObject> // convert NSArray to Array of AnyObject
let arr3 = arr2.filter { [=11=] 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