Joe Longstreet Joe Longstreet - 4 months ago 20x
Swift Question

Ambiguous reference to member 'delegate'

I'm trying to create an instance of a singleton class written in Objective-C. I must conform to it's delegate protocol. The Swift implementation looks something like this:

class SomeClass: ManagerDelegate {
let manager = Manager.sharedInstance()

func someFunction(){
manager.delegate = self

The Objective-C singleton class looks something like this:

// header
@protocol ManagerDelegate <NSObject>

@interface Manager : NSObject {

+ (id)sharedInstance;
@property (nonatomic, assign) id delegate;

// class file
+ (id) sharedManager{
static Manager *theSharedManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
theSharedManager = [[self alloc] init];

return theSharedManager;

- (void) someInternalMethod{
[delegate delegateMethod];

Upon specifying the delegate (
manager.delegate = self
), I receive the error

Ambiguous reference to member 'delegate'

Is the Objective-C class improperly formed or am I implementing it incorrectly? Am I missing something else?


Your problem is caused by the definition of your sharedInstance method in Objective-C. By declaring it as

+ (id)sharedInstance;

it gets converted to sharedInstance() -> AnyObject! in Swift. Swift then doesn't know which of many potential delegate properties that it can find you mean. If you change your Objective C declaration and implementation to be:

+ (instancetype)sharedInstance;

your problem will go away.

And as @rmaddy points out, your delegate should be weak not assign. If you use assign then delegate will be left as an invalid pointer in the event that the delegate is deallocated.

Also, the use of a delegate with a singleton is a bit contradictory. Given that you will only ever have one instance of the Manager which may be used by a number of other objects and you can only have one active delegate at a time there is the potential for conflicts.

I would suggest that either blocks/closures or NSNotification is a better approach to call backs from a singleton.