2

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.

5

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

how to call needToImplementThis or canImplementThis in objective-c?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.