Swift class/struct 隐式符合 NSObjectProtocol?

Swift class/struct implicitly conforms to NSObjectProtocol?

不久前我遇到了一个奇怪的 Swift 问题。当我尝试在调试中将 Swift 对象转换为 NSObjectProtocol - 它成功执行。但是当这段代码在 AppStore build 中执行时,它会转换为 nil。

import Foundation

final class MyClass {
    let testP: String = "123"
}

struct MyStruct {
    let testP: String = "123"
}

let myClass = MyClass()
let myStruct = MyStruct()

print(myClass) // >> __lldb_expr_1.MyClass
print(myClass as! NSObjectProtocol) // >> __lldb_expr_1.MyClass
print(myStruct as! NSObjectProtocol) // >> __lldb_expr_3.MyStruct(testP: "123")

当我将结构转换为 NSObjectProtocol 时,我收到这样的警告:

Cast from 'MyStruct' to unrelated type 'NSObjectProtocol' always fails

但是,您如何看到它成功打印了我的结构。

所以,问题是:它是 Swift 的错误还是功能?)

PS: 请原谅我的法语

NSObjectProtocol有一些AnyClass的方法,你需要遵守协议的方法。

您可以在 Apple 官方阅读的内容 documentation

An object that conforms to this protocol can be considered a first-class object. Such an object can be asked about its:

Class, and the place of its class in the inheritance hierarchy.

Conformance to protocols.

Ability to respond to a particular message.

在图像中查看使任何对象符合 NSObjectProtocol 的方法。

这里还有一些对您有用的信息:https://medium.com/a-swift-misadventure/why-swift-protocol-conforming-values-are-treated-as-value-types-by-default-9482c6809583

显然,它既是错误又是功能。 https://bugs.swift.org/browse/SR-10495