Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding delegate protocol conformance to pure swift class

I am using a package that declares an open class A, which I can't modify.

In my code, I'd like to declare class B as inheriting from this A class, and also conform to a delegate protocol (HMHomeManagerDelegate in my case).

class B: A, HMHomeManagerDelegate {

The compiler is telling me : "Cannot declare conformance to 'NSObjectProtocol' in Swift; 'HomesList' should inherit 'NSObject' instead" - and that's because HMHomeManagerDelegate inherits from NSObjectProtocol, and I shall therefore provide all NSObjectProtocol's required methods in B.

But that means a lot of boiler plate code (some of which being non-trivial)...

Is there any better pattern ?

like image 924
AirXygène Avatar asked Sep 16 '25 02:09

AirXygène


1 Answers

One of possible options is to make a separate class MyHome, which implements HMHomeManagerDelegate, and then use it inside of class B.

class MyHome: NSObject, HMHomeManagerDelegate { ... }

class B: A {
    let myHome = MyHome()

    // and all communication with HomeKit will go through MyHome class
    // ...
}

If your project is small, I guess MyHome will look like a useless wrapper. But in a bigger application I can imagine that MyHome is responsible for convenient communication with HomeKit, so class B makes decisions while MyHome serves it (prepares/modifies some data which goes to/from HomeKit).

like image 197
alexander.cpp Avatar answered Sep 19 '25 04:09

alexander.cpp