按类型过滤Swift数组的奇怪行为

时间:2015-08-16 09:34:35

标签: swift swift2

有人可以向我解释为什么下面的代码似乎无法区分数字类型吗?

extension Array {
    func filterByType<T>(type: T.Type) -> [T] {
        var r = [T]()
        for case let m as T in self {
            r += [m]
        }
        return r
    }
    func filterByType2<T>(type: T.Type) -> [T] {
        var r = [T]()
        for m in self {
            if m is T {
                r += [m as! T]
            }
        }
        return r
    }
}

let objects = [1, "2", 3, "4", 5.1, [1, 2]]

typealias IntArray = [Int]

objects.filterByType(String.self) // ["2", "4"] - as expected
objects.filterByType(IntArray.self) // [[1, 2]] - as expected
objects.filterByType(Double.self) // [1, 3, 5.1] - ok, but surprised 1 & 3 aren't Ints
objects.filterByType(Int.self) // [1, 3, 5] - why?

objects.filterByType2(String.self) // ["2", "4"] - as expected
objects.filterByType2(IntArray.self) // [[1, 2]] - as expected
objects.filterByType2(Double.self) // [1, 3, 5.1] - ok, but surprised 1 & 3 aren't Ints
objects.filterByType2(Int.self) // [1, 3, 5] - why?

1 个答案:

答案 0 :(得分:1)

对象数组推断为NSObject类型,数字类型为NSNumber,可以投放到IntDouble甚至{{1} (可能是意外的)。

因此,为了获得所需的行为,您应该明确地将数组的类型声明为Bool

作为算法的改进,我建议使用[Any]

flatMap