简体   繁体   中英

Converting Objective-C based Delegate to Swift

Currently I am trying to convert Objective-C code to Swift, and facing some issue with delegate of id type.

Below is the code as following:

@property (weak, nonatomic) id <TestDelegate> delegate;

During initialization time, there is a controller being send and set as a delegate like this:

- (instancetype)initWithController:(id)controller {
   self = [super init];
   if (self) {
      self.delegate = controller;
   }
   return self;
}

As you can notice, since the delegate here is an id type which can keep of any kind of reference, it is storing the reference of the controller for delegate, and the controller that is being passed is conforming the protocol of "TestDelegate". However, I am curious how can you achieve this in swift?

Thanks

I think the id type maps to "Any". This is dangerous, and should probably be replaced with actual type in swift:

weak var delegate: TestDelegate?

init(delegate: TestDelegate) {
  self.delegate = delegate
}

If dealing with reference types, you'd generally define your protocol as a class protocol:

protocol TestDelegate: class {
    ...
}

And then make your delegate property weak :

class Foo {
    weak var delegate: TestDelegate?

    init(delegate: TestDelegate) {
        self.delegate = delegate
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM