【问题标题】:protocol as parameter type in swift conflicts协议作为 swift 冲突中的参数类型
【发布时间】:2015-03-20 15:50:15
【问题描述】:

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

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

请检查以下 swift 代码,后跟我的 # cmets

//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中使用相同的类名和方法名,即在我的例子中是CustomView。如果我使用 CustomView 来声明对象,我不能使用它作为方法名。

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

【问题讨论】:

    标签: ios objective-c xcode swift ios8


    【解决方案1】:

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

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

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

    假设在 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!) {
        }
    }
    

    【讨论】:

    • 感谢@rintaro,第二个选项对我有用,即 typealias。
    【解决方案2】:

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

    而不是调用:

    var customview : CustomView = CustomView()
    

    你可以打电话:

    var customview : CustomView = CustomView.init()
    

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

    【讨论】:

    • 感谢@Chackle 的快速响应和有关 swift 的新信息,但不幸的是,它并没有解决我的问题,它仍然给出同样的错误。
    猜你喜欢
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多