Search code examples
iosswiftcastingnsobjectprotocol

Swift class/struct implicitly conforms to NSObjectProtocol?


A while ago I faced strange Swift issue. When I try to cast Swift object to NSObjectProtocol in debug - it executes successfully. But when this code executes in AppStore build, it casts to 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")

When I cast struct to NSObjectProtocol I get such warning:

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

However, how you can see it successfully prints my struct.

So, the question is: is it bug or feature of Swift?)

PS: Pardon my French 😀


Solution

  • Apparently, it’s both bug and feature. https://bugs.swift.org/browse/SR-10495