swift - 为什么通用函数在转换为相同类型时会崩溃?

标签 swift

这是一些 Playground 代码:

func getNone<T>() -> T {

    print(T.self)

    let none: Bool? = nil

    return none as! T
}

let noMore: Bool? = getNone()

但是,此代码会导致在展开可选错误时发现 nil。我想知道为什么会发生这种情况,因为在这种情况下 T 显然是 Bool? - 来自 print 语句 - 并将 nil 转换为Bool? 不会导致此错误。

最佳答案

在我看来,这像是 Swift 中的一个错误。我什至添加了更多打印语句来突出显示这一点:

func getNone<T>() -> T {
    let none: Bool? = nil
    print(type(of: none) == T.self) // prints "true"
    print(none is T) // prints "false". How can that be given the above is true?
    return none as! T // crashes
}

let noMore: Bool? = getNone()

更新:

围绕类似/相关行为已经提交了一些错误。例如:

https://bugs.swift.org/browse/SR-4248

https://bugs.swift.org/browse/SR-158

他们建议使用 Hamish 在下面的评论中指出的相同解决方法。在这种情况下,几乎可以确认您确实偶然发现了一个 Swift 错误。

关于swift - 为什么通用函数在转换为相同类型时会崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47823706/

相关文章:

ios - 尝试在重新排序已经在进行时开始对 Collection View 重新排序

ios - 如何在 iPad 上打造无边框 Swift Playgrounds?

ios - 包括 Split View在内的整个屏幕的 Swift iOS 屏幕截图

ios - AWS Mobile Hub 集成链接器错误 "Mach-O"

iOS 沙发底座 : Shared CBL manager between app and app extension

swift - AVAssetWriter 在 Swift 中录制视频?

ios - SKProduct RequestDelegate 离开 View 时崩溃

swift - 在 ViewDidLoad 中声明一个变量并在其他地方使用 (Swift)

ios - 如何从 cloudkit 中获取所有记录

iOS Swift4 没有请求 App 权限