[英]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.