Swift 5.1 不透明结果类型如何与旧操作系统交互(例如 iOS 12)

How do Swift 5.1 Opaque Result Types interact with older OSs (e.g. iOS 12)

在 WWDC 2019 session 402“What's New in Swift", the speaker, when discussing the Swift 5.1 feature Opaque Result Type (SE-0244) 中,提到该功能仅适用于新的 OSes:

Requires new Swift runtime support

    Available on macOS Catalina, iOS 13, tvOS 13, watchOS 6 and later

    Guard uses with availability checking when deploying to earlier OS releases

在 Xcode 11 中,如果我使用此功能编写代码,并且针对 iOS 11 及更高版本,我不会收到任何构建错误(或警告)。我没有在 if #available(iOS 13.0, *) 检查中包含任何代码。例如:

protocol Shape { }
class Square: Shape { }
class Triangle: Shape { }
    
func foo() -> some Shape {
    return Square()
}

然后从我的应用中的一些代码调用 foo()

如果此代码在 iOS 13 之前的设备上运行会怎样?缺少构建错误本身就是错误吗?是否有明确的列表,其中 Swift 5.1 功能需要新的运行时支持,因此需要特定的 OS 版本?

Is the lack of build error itself an error?

是的。并且有明确的记录。 release notes 清楚地告诉你:

Declarations with some Protocol return types require the Swift 5.1 runtime in iOS 13, macOS 10.15, watchOS 6, or tvOS 13, but the Swift compiler doesn’t enforce this. Running an app that uses some return types on previous operating system versions might crash at runtime... Workaround: Only deploy binaries that use some return types to iOS 13, macOS 10.15, watchOS 6, and tvOS 13. Avoid them in code that must run on previous operating system versions.

所以,照你说的做:使用availability守卫或者准备去死。

编辑 这个错误现已修复,这意味着 some return 类型的可用性由编译器强制执行: