![]() (And it’s worth mentioning that the same issue affects the extension approach.) Unfortunately, this pollutes the public interface of the class, but I don’t think there’s a way around that. You’ll have to make them “public” by moving the declarations to the header file to be able to use them in Swift. members that aren’t declared in the header file), those won’t be visible to the subclass. If your Objective-C class has any “private” properties or methods (i.e. Unlike the extension pattern, adding stored properties to the subclass is no problem.Īccessing “private” superclass members in the subclass Use annotations where necessary to expose the new functionality to Objective-C clients. ![]() Write your new code in the Swift subclass. ![]() This is the reason these classes (if they exist) must be written in Swift because Swift/Clang doesn’t support subclassing a Swift class in Objective-C. Subclasses of the original class will now also have the Swift class as their superclass. The only thing you may have to do is #import the Xcode-generated Swift header in places that use NetworkService. Since you’re reusing the class name, clients will automatically use the Swift subclass from now on, without you having to change anything. Add the class header to your Swift bridging header.Ĭreate a Swift class that inherits from the Objective-C class and uses the original name:Ĭlass NetworkService : _NetworkService by adding an underscore: NetworkService becomes _NetworkService. We need an additional constraint: the subclassing approach only works if the Objective-C class doesn’t have any Objective-C subclasses and you’re not planning to add any in the foreseeable future. ![]() I’ll use the same scenario as in part 1: you have a fairly large Objective-C class and you want to add a feature to it in Swift, without converting the entire class to Swift. But another great solution I adopted successfully for a very large class was to rename ObjC HHFooBar into _HHFooBar and redefine HHFooBar as a Swift subclass of _HHFooBar. Following up on last week’s article on migrating an Objective-C class to Swift using extensions, I’d like to discuss an alternative approach: adding a Swift subclass to the Objective-C class you want to convert, as suggested by Jérôme Alves (thanks!): ![]()
0 Comments
Leave a Reply. |