r/ObjectiveC • u/whackylabs • Feb 23 '20
Objective-C safe downcasting
https://whackylabs.com/objc/swift/2020/02/23/objc-safe-downcasting/
5
Upvotes
r/ObjectiveC • u/whackylabs • Feb 23 '20
7
u/mariox19 Feb 23 '20 edited Feb 23 '20
I think this is a misguided idea. Look:
To me, this kind of down-casting (if we're talking about Objective-C programming) is a code smell. It starts here:
It's not the subclassing that's the problem, it's the use of the Class Factory Method. I would never use a CFM and return objects with different public interfaces. I think it is even a huge mistake to describe the return type as an
instancetype. The interface should look like this:What's going on in this whole discussion is not Object-Oriented Programming. The implementation is leaking through the interface. Moreover, down-casting is not idiomatic Objective-C. Casting happens at runtime. An Objective-C programmer, traditionally, would check to see if an object responds to a message, not test what kind of object an object is.
Swift is not a dynamic language. Just because something is done in Swift (or C++, or whatever) does not mean it should be done in Objective-C.
P.S.
Get off my lawn!
6
u/[deleted] Feb 23 '20
This is the sort of thing that Apple should have extended ObjC with.
4
u/[deleted] Feb 23 '20
Here’s the thing objc_msgSend will lookup the requested method. And execute it if found. And if it finds the one in the subclass it will execute that one. Hardly any magic if you ask me.