简体   繁体   English

将基于Objective-C的委托转换为Swift

[英]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. 目前,我正在尝试将Objective-C代码转换为Swift,并遇到ID类型委托的问题。

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". 如您所见,由于这里的委托是一个ID类型,可以保留任何类型的引用,因此它存储了委托的控制器的引用,并且正在传递的控制器符合“ TestDelegate”的协议。 However, I am curious how can you achieve this in swift? 但是,我很好奇您如何迅速实现这一目标?

Thanks 谢谢

I think the id type maps to "Any". 我认为id类型映射为“ 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: 如果处理引用类型,通常将协议定义为class协议:

protocol TestDelegate: class {
    ...
}

And then make your delegate property weak : 然后使您的delegate属性weak

class Foo {
    weak var delegate: TestDelegate?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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