2

I'm trying to have an Objective-C class adopt a protocol written in a Swift file. I've got Swift an Objective-C inter-operating to some extent. (I can construct my Objective-C class from Swift).

I have:

@objc public protocol FooProtocol {
    func foobar()
}

Then, my Objective-C file:

#import <UIKit/UIKit.h>
#import "SwiftObjcProtocolTest-Bridging-Header.h"

@protocol FooProtocol
@end

@interface ObjClass1 : NSObject <FooProtocol>

-(void)foobar;

@end

and impl:

#import "ObjClass1.h"

@implementation ObjClass1

- (void)foobar {
    NSLog(@"foobar protocol function called");
}

@end

But when I give Swift (doing this mostly in app delegate) a delegate property and try to assign the Objective-C object to it:

var delegate: FooProtocol?
....
delegate = objcInstance
delegate?.foobar()

it fails with:

cannot assign value of type 'ObjClass1' to type 'FooProtocol?'.

I've tried coercing it with as! FooProtocol but this results in a SIGABRT.

What is the issue here?

Alex Bollbach
  • 4,370
  • 9
  • 32
  • 80

1 Answers1

0

To get this working I found that:

  1. Make sure to import your Swift code into Objective-C (see here). Import it into ObjClass1.m.
  2. Your forward declaration of the protocol FooProtocol should look like this:

    @protocol FooProtocol;
    

instead of:

    @protocol FooProtocol
    @end

Note: Although this worked for me, there is probably a better solution out there as I get a warning in ObjClass1.h saying Cannot find protocol definition for 'FooProtocol'.

paulvs
  • 11,963
  • 3
  • 41
  • 66
  • 1
    i get the warning you mentioned twice ( the warning is repeated indicated to me Xcode isn't doing too fell with my setup). Also. i'm getting `I_OBJC_PROTOCOL_$_FooProtocol, referenced from:` and than nothing. and `linker command failed with exit code (-v for more..)`. and whats odd is clicking these errors doesn't even take me to more information further indicating something is buggy or not setup right here. – Alex Bollbach May 28 '17 at 18:27