swift – 为什么unsafeBitCast不是编译器错误?

以下代码失败的一般问题已经是
answered了.但我的问题是,如果它永远不可能,为什么这不是编译器错误?

这是一个最小的例子:我可以定义这个函数,即使unsafeBitCast总是会失败,编译器也不会抱怨:

func foo() -> [Int] {
    let arr: [Int?] = [1, 2, 3, 4]
    guard let barr = arr as? [Int] else { return [] }
    return barr
}

在我们实际尝试在运行时调用foo()之前,这不会失败.

最佳答案 这是一个编译器错误,因为[Int]不是[Int?]的子类型所以,你的代码不应该编译而没有任何错误.但是,下一个代码应该按预期工作

let i: [Int?] = [1,2,3]
let d: [Double?] = [1,2,3]

func foo<T>(arr:[T?]?) -> [T] {
    guard let barr = arr where T.self == Int.self else { return [] }
    return barr.flatMap{ $0 }
}

print(foo(i), foo(i).dynamicType)
print(foo(d), foo(d).dynamicType)
/*
 [1, 2, 3] Array<Int>
 [] Array<Double>
 */

请填写错误报告!更有趣的是,下一代码无法编译

let j = [Optional(1),Optional(2)] as? [Int]

let j = [Optional(1),Optional(2)]
let k = j as? [Int]

编译和崩溃……

let arr0:[Int?]? = [1,2,3]

if let r = arr0 where r.dynamicType == [Int].self {
    print(r, r.dynamicType)
} else {
    print("not [Int]")
}
// prints 
// not [Int]

// but
func foo()->[Int] {
    let arr0:[Int?]? = [1,2,3]
    if let r = arr0 where r.dynamicType == [Int].self {
        print(r, r.dynamicType)
        // !!!!! ERROR !!!!!
        // next line doesn't compile wihout flatMap !!!!
        //
        // error: cannot convert return expression of type '[Int?]' to return type '[Int]'
        //
        // even though that it is clear from the where clause that r type must be [Int]
        return r.flatMap{ $0 }
    } else {
        print("arr0 is not [Int]")
        return []
    }
}
foo() // [] and prints: arr0 is not [Int]
点赞