doom4d.h
doom4d.h

Reputation: 63

Swift cannot pass class conforming to protocol as function parameter to a function residing in Objective-C file

Hi I'm new to Swift but experienced with Objective-C. I have a project that uses both Swift and Objective-C files (bridging and all).

Say I have a protocol called "fooProtocol" and a class "foo" that implements it. I am trying to pass an object of type "fooProtocol" from the Swift file as a parameter to the function inside the Objective-C file.

here is the Objective-C function inside class "tester":

-(void)setWithFoo:(id<fooProtocol>*)_foo{ }

here is the Swift code:

var myObject:fooProtocol = foo.init() var objcObject:tester = tester.init() objcObject.setWithFoo(_foo: myObject)

It first says "Cannot convert value of type "fooProtocol" to expected argument type "AutoreleasingUnsafeMutablePointer (obviously because it needs to be passed by reference, so...)

I then tried casting the parameter to this:

tester.setWithFoo(_foo: AutoreleasingUnsafeMutablePointer<fooProtocol>(myObject))

Now the error reads: "Cannot invoke initializer for type 'AutoreleasingUnsafeMutablePointer with an argument list of type '(fooProtocol)'

I have tried many more permutations and variations but I simply cannot stop the compiler error. For such a simple procedure as passing a polymorphic variable to a function in Objective-C file that expects that protocol id, Swift has made it a nightmare.

...Any help would be appreciated, thanks!

=== EDIT ===

Here are the declarations for the classes, now starting properly with caps

In the "FooProtocol.h" file:

@protocol FooProtocol
@end

In the "Foo.h" file:

#import <Foundation/Foundation.h>
#import "FooProtocol.h"

@interface Foo : NSObject <FooProtocol>
@end

In the "Foo.m":

#import "Foo.h"

@implementation Foo
@end

The "FooProtocol.h" file:

#import <Foundation/Foundation.h>

@protocol FooProtocol
@end

The "Tester.h" file:

#import <Foundation/Foundation.h>
#import "FooProtocol.h"

@interface Tester : NSObject
-(void)setWithFoo:(id<FooProtocol>*)_foo;
@end

The "Tester.m" file:

#import "Tester.h"

@implementation Tester

-(void)setWithFoo:(id<FooProtocol>*)_foo{
    //do something with _foo
}
@end

And again the Swift code that can't compile:

var myObject:FooProtocol = Foo.init()
var objcObject:Tester = Tester.init()
objcObject.setWithFoo(AutoreleasingUnsafeMutablePointer<FooProtocol>(myObject))

Upvotes: 2

Views: 689

Answers (1)

matt
matt

Reputation: 535304

You probably don't mean to say this:

-(void)setWithFoo:(id<FooProtocol>*)_foo;

It is very unusual to see an id* in Objective-C. In fact, it's so unusual that in all my years of programming Cocoa, I have never seen one.

You probably mean this:

-(void)setWithFoo:(id<FooProtocol>)_foo;

And then you will be able to say, on the Swift side:

objcObject.setWithFoo(myObject)

Upvotes: 3

Related Questions