[英]protocol as parameter type in swift conflicts
我正在使用外部SDK(通过将xcode项目包含在我的项目中)。 SDk在Objective-c中正常工作,但是当我切换到swift时,我遇到了以下问题。
每当我实现参数类型为协议的委托方法时,xcode都会突然给该类的对象声明产生错误,该类声明是全局声明的,即未在任何函数中声明。 如果我评论该特定的委托方法,我将不会收到任何错误,并且可以成功编译/执行。
请检查以下快速代码,然后加上我的#条注释
//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而言都可以正常运行,但对于迅速而言却不是。
根据我的研究,我得出结论,我们不能迅速使用相同的类名和方法名,即我的情况是CustomView。 如果我使用CustomView声明对象,则不能将其用作方法名称。
所以有人请确认我是正确的吗? 以及该问题的解决方案是什么。
从本质上讲,这是一个名称冲突的问题。
在类声明中, CustomView
是方法名称,而不是类名称。 因此,基本上,您的假设是正确的。
但是,您有一种解决方法。
假设在SDK中声明了CustomView
。 那就是一个名为SomeSDK
的框架。 然后,您可以像这样引用CustomView
:
import SomeSDK
class ViewController: UIViewController {
var customview: SomeSDK.CustomView = SomeSDK.CustomView()
func CustomView(view: AnyObject!, didFailWithError error: NSError!) {
}
}
如果您不想在SomeSDK.
前缀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!) {
}
}
我可能是错的,但是看来您也可以迅速调用init函数。
而不是调用:
var customview : CustomView = CustomView()
您可以致电:
var customview : CustomView = CustomView.init()
这在我的游乐场中有效,让我知道如何为您工作。 这将允许您按原样使用函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.