Can I make my Objective-C class Codable?

I have an Objective-C class that I use from Swift:

// Simplified
@interface MASShortcut : NSObject <NSSecureCoding, NSCopying>
@property (readonly) NSUInteger keyCode;
@property (readonly) NSUInteger modifierFlags;
@end

Can I make the class conform to Codable out of the box, without wrappers? (I “own” the class, I can make changes to the framework.)

No. Although Obj-C classes can conform to Swift protocols, Decodable includes an initialiser requirement. So you can't add it to a non-final class.

There doesn't seem to be a way to mark an Obj-C class as "final" in a way that is sufficient for Swift. Even the objc_subclassing_restricted attribute doesn't entirely rule out that subclasses might exist:

__attribute__((objc_subclassing_restricted))
@interface Testclass : NSObject
@end

__attribute__((objc_subclassing_restricted))
@interface Testclass2: Testclass
@end
4 Likes
Terms of Service

Privacy Policy

Cookie Policy