swift 冲突中作为参数类型的协议

protocol as parameter type in swift conflicts

我正在使用外部 SDK(通过在我的项目中包含他们的 xcode 项目)。 SDK 在 objective-c 中正常工作,但是当我切换到 swift 时,我遇到了以下问题。

每当我实现参数类型为协议的委托方法时,xcode 突然给全局声明的 Class 的对象声明错误,即不在任何函数中。如果我评论那个特定的委托方法,我将不会收到任何错误并且它 compile/executes 成功。

请检查以下 swift 代码,然后是我的 # 评论

//CustomView is subclass of UIView
        var customview : CustomView = CustomView() // #1 error as : Use of undeclared type CustomView
        @IBAction func showCustomView(sender: AnyObject) 
        {    
        // CustomView configurations 
        }

    #pragma CustomView Delegates
        func CustomViewShown(view: AnyObject!) /// #2 delegate work properly
        {

        }

        func CustomView(view: AnyObject!, didFailWithError error: NSError!) 
    // #3 if I keep this method uncommented it gives error to #1 line  
    // if I commented this method all other works fine without error.
        {

        }

令人惊讶的是,上述所有委托和 SDK 在 objective-C 上工作正常,但在 swift.

上却不行

根据我的一些研究,我得出的结论是, 我们不能在 swift 中使用相同的 Class 名称和方法名称,即在我的例子中是 CustomView。如果我使用 CustomView 来声明对象,我不能将它用作方法名称。

所以有人请验证一下,我是否正确?这个问题的解决方案是什么。

我可能是错的,但似乎在 swift 你也可以显式调用 init 函数。

而不是调用:

var customview : CustomView = CustomView()

您可以拨打:

var customview : CustomView = CustomView.init()

这在我的 Playground 中有效,让我知道它对您的效果如何。这将允许您使用按原样命名的函数。

本质上是一个名称冲突问题。

在您的 class 声明中,CustomView 是一个方法名称,而不是 class 名称。所以,基本上,你的假设是正确的。

但是,您有一个解决方法。

假设在 SDK 中声明了 CustomView。那就是一个名为 SomeSDK 的框架。然后你可以像这样引用 CustomView:

import SomeSDK

class ViewController: UIViewController {

    var customview: SomeSDK.CustomView = SomeSDK.CustomView()

    func CustomView(view: AnyObject!, didFailWithError error: NSError!) {
    }
}

如果你不想到处加前缀SomeSDK.,你可以typealias它:

import SomeSDK

typealias SDKCustomView = CustomView // you can use `CustomView` here because there is no conflicting name.

class ViewController: UIViewController {

    var customview: SDKCustomView = SDKCustomView()

    func CustomView(view: AnyObject!, didFailWithError error: NSError!) {
    }
}