Implementing Objective C delegate in Swift

狂风中的少年 提交于 2021-01-28 04:41:09

问题


I have a Objective C class that has methods that look like this:

@class Client;

@protocol ClientDelegate <NSObject>

@optional
-(void) receivedMessageFromClient : (id) message;

@end

@interface Client : NSObject 

+(id) setup; 
 @property(nonatomic, strong) id <ClientDelegate> clientDelegate;

// more method declarations below

I am implementing the ClientDelegate in my Swift class like this:

class HomeViewController: UIViewController, ClientDelegate {
    var client : AnyObject?
    var delegate: ClientDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

        client = Client.setup() as! Client
         client.clientDelegate = self
    }

func receivedMessageFromClient(message: AnyObject) {
        print("Message recieved: \(message)")
    }
}

This is giving me a compiling error:

Cannot assign to property: 'self' is immutable

When I remove the lines

client = Client.setup() as! Client
client.clientDelegate = self

the code compiles and calls the method in the Client class that in turns sends a message to receivedMessageFromClient, but the method is not called in HomeViewController. It seems that everything is setup with the exception of assigning self to be the delegate.


回答1:


Check out my comments on your question but this is a basic example of an Objective-C delegate implemented in Swift:

Objective-C:

@protocol MyDelegate <NSObject>

@optional
- (void)canImplementThis:(int)aVar;
@required
- (BOOL)needToImplementThis;

@end

@interface MyClass : NSObject

@property (nonatomic, weak) id<MyDelegate> delegate;

@end

Swift:

class SwiftClass : UIViewController, MyDelegate {

    var myObj : MyClass?

    override func viewDidLoad() {
        super.viewDidLoad()

        myObj = MyClass()
        myObj?.delegate = self
    }

    // MARK: - <MyDelegate>

    func canImplementThis(aVar : Int) {
        print("Called: \(aVar))
    }

    func needToImplementThis() -> Bool {
        return false
    }

}

Forgive any typos I typed this out straight into SO.




回答2:


Had to change Int to Int32 for some reason so it fix the invalid selector issue, with Int32 on the swift side but then worked



来源:https://stackoverflow.com/questions/33821912/implementing-objective-c-delegate-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!