Using the Swift Protocol Implementation in Obj-C

I am trying to implement an intermediary template with a mixture of Swift and Obj-C. The problem I ran into is how to deal with using the Swift protocol implementation classes from Obj-C. Check out the code to understand what I mean:

Swift protocol and its implementation:

@objc public protocol TheProtocol {
    func someMethod()
}

@objc public class SwiftClass: NSObject, TheProtocol {
    public func someMethod() {
        print("someMethod Swift")
    }
}

ObjC protocol implementation:

#import "SwiftAndObjC-Swift.h"
@interface ObjCClass : NSObject <TheProtocol>
- (void) someMethod;
@end


@implementation ObjCClass
- (void) someMethod
{
    NSLog(@"someMethod ObjC");
}
@end

My question is how can I define some type in ObjC that is able to reference SwiftClass or ObjCClass. For example, this does not compile:

#import "SwiftAndObjC-Swift.h"
...
TheProtocol *p = [[ObjCClass alloc] init];
// Error: "Use of undeclared identifier TheProtocol"

This will compile:

@class TheProtocol
TheProtocol *p = [[ObjCClass alloc] init];

But you cannot use p:

@class TheProtocol
TheProtocol *p = [[ObjCClass alloc] init];
[p someMethod];
// Error: Receiver type "The Protocol" is a forward declaration"

(Adding casts to the destination and / or method call does not help)

Any solutions?

+4
source share
3 answers

Objective-C . :

id<TheProtocol> p = [[ObjCClass alloc] init];

, , , , , - , , .

( id p =...).

Swift - :

class MyClass : Superclass, Protocol, AnotherProtocol { ... }

Objective-C :

@class MyClass : SuperClass <Protocol, AnotherProtocol>
// ... 
@end

? Swift , Objective-C -.

, -.

id ObjectiveC AnyObject? Swift. , SomeProtocol, , AnyObject id Objective-C.

+11

@class ... Swift, .

, , Obj C, id<TheProtocol>

-1

Decided I just changed the type to id

id p = [[ObjCClass alloc] init];
[p someMethod];
-2
source

All Articles