[swift-users] Cannot subclass a class with objc_subclassing_restricted attribute

Rod Brown rodney.brown6 at icloud.com
Mon Apr 17 09:01:10 CDT 2017


Hi Rick,

Unfortunately, that is the case. You cannot subclass a Swift class (even if it is a subclass of NSObject and available to the Objective-C runtime) because of deliberate limitations baked into Obj-C to block subclassing Swift classes in Obj-C code.

I believe the reason for this limitation is that Swift includes features that cannot be utilised in Obj-C and therefore subclasses would be restricted and would get undefined behaviour when implementing methods that cannot cross into Obj-C.

If Apple were to allow Obj-C -> Swift -> Obj-C subclassing, then it would be on a limited basis. Some methods wouldn’t do the same thing in Swift as they would in Obj-C selectors, and you could theoretically declare conflicting methods in your subclass that would have different actions depending on whether you were addressing the class in Swift and Obj-C. Additionally, the Swift Compiler couldn’t see beyond the Swift barrier and therefore may make optimisations that would break your Obj-C subclasses.

While I understand the frustration behind this, both in personal projects and philosophically, I think that this is unfortunately the better of the two options.

- Rod


> On 15 Apr 2017, at 12:41 pm, Rick Mann via swift-users <swift-users at swift.org> wrote:
> 
> I'm refactoring some Objective-C code to inherit from a new Swift super class. This has been going okay, and I've been cleaning up build errors as I spot them (some auxiliary enums caused enum name changes, etc.).
> 
> But my last error seems to be that I can't subclass the Swift class: "Cannot subclass a class with objc_subclassing_restricted attribute". I didn't notice it before, and all the online references that say you can't subclass a Swift class point to a Swift document that no longer mentions that. They also don't say what they mean by "Swift" class (e.g. is it not marked with @objc?).
> 
> In any case, my Swift class looks like:
> 
> @objc
> class
> Camera : NSObject
> {
>    ...
> }
> 
> And my ObjC class looks like:
> 
> @interface
> MCPCamera : Camera
> 
>    ...
> 
> @end
> 
> I feel like this is a reasonable thing to try to do. Is it just not possible?
> 
> -- 
> Rick Mann
> rmann at latencyzero.com
> 
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users



More information about the swift-users mailing list