2

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

Dmitriy Stupivtsev
  • 832
  • 1
  • 8
  • 17

2 Answers2

0

NSObjectProtocol has some methods for AnyClass and you need to conform with protocol's methods.

What you can read in offical 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.

See in an image a methods to conform any object with NSObjectProtocol. enter image description here

Some other helpful information for you here: https://medium.com/a-swift-misadventure/why-swift-protocol-conforming-values-are-treated-as-value-types-by-default-9482c6809583

Agisight
  • 1,778
  • 1
  • 14
  • 15
0

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

Dmitriy Stupivtsev
  • 832
  • 1
  • 8
  • 17