将ObjC返回类型(id <protocol>)转换为其Swift 3.0等效项

时间:2016-11-08 20:45:31

标签: objective-c swift3 protocols return-type

我对如何将Objective-C方法签名转换为其Swift 3.0等价物感到困惑。

以下是使用返回类型&#39; id&#39;的原始Objective-C方法。使用其UIViewControllerAnimatedTransitioning协议:

目标C

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    return self;
}

我希望将Objective-C版本转换为相应的Swift 3.0等价物:

Swift 3.0

func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return self
    }

Swift 3.0版本是否正确?

...或者我应该使用 AnyObject?返回类型:

enter image description here ......我从中得到了警告;那么处理(id)签名呢?

更具体地说,应该&#39; id&#39;被翻译成协议?类型?

这是编译器&#34;解决方案&#34;: enter image description here

什么是正确的格式?

这是编译器返回的内容: enter image description here

2 个答案:

答案 0 :(得分:2)

是的,在将id<SomeProtocol>从ObjC翻译为Swift时,协议名称就是完整类型。 (你不需要翻译任何符合协议的东西id。协议来自ObjC,所以唯一符合它的东西就是对象 - 也就是说,你的协议隐含了AnyObject的子类型。)

在您的情况下,optional func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?也是the official translation of that delegate method signature

将方法声明为返回AnyObject?会破坏委托方法签名,这将无法正常工作,因为它与正确的方法共享相同的ObjC选择器。 (并且使不正确的签名@nonobjc保证不会被调用。)

答案 1 :(得分:0)

根据ricster的回答,我重新检查了我的代码。

我发现我没有在主机(self)中采用每个所述Objective-C源的协议,因此得到了Swift 3.0编译器投诉:

enter image description here