2015-11-04 42 views
0

我是Swift初學者,並且確實遇到了這個問題。Swift正確聲明與協議相對應的對象並且擁有超類

我有一個原型單元CurrencySwitchTableViewCell,它是UITableViewCell的子類。

class CurrencySwitchTableViewCell: UITableViewCell { 
     @IBOutlet weak internal var currencySwitchDelegate: AnyObject! 

該電池具有currencySwitchDelegate屬性,它應該是CurrencySwitchDelegate協議的

protocol CurrencySwitchDelegate { 
    func didSelectCurrency(currency:Currency) 
} 

我怎樣才能在CurrencySwitchTableViewCell聲明,我currencySwitchDelegate對應CurrencySwitchDelegate協議AnyObject

什麼是這樣的Objective-C代碼的Swift模擬?

NSObject<CurrencySwitchDelegate>id<CurrencySwitchDelegate>

附:

我知道我可以宣佈我的財產是

@IBOutlet weak internal var currencySwitchDelegate: CurrencySwitchDelegate! 

不過了XCode給我的錯誤與@IBOutlet修飾符(IBOutlets應該AnyObject類)

+0

我也是Swift的初學者,但是你不需要聲明'CurrencySwitchDelegate'是'AnyObject'的協議嗎? –

+0

你爲什麼使用@IBOutlet?你是通過接口生成器連接的東西嗎?通常它應該是'var currencySwitchDelegate:CurrencySwitchDelegate?' –

+0

我使用iboutlet來設置從我的單元到實現此協議的viewcontroller的連接 –

回答

1

的對象有經常弱參考委託和只有對象可能成爲弱引用。您可以通過使用: class

protocol CurrencySwitchDelegate: class { 
    func didSelectCurrency(currency:Currency) 
} 

眼下的Xcode不能IBOutlet中協議告知編譯器,這個委託是一個對象。臨時解決方案是創建一個AnyObject類型的其他IBOutlet,然後將其轉換爲代碼。

@IBOutlet weak internal var outletDelegate: AnyObject? 

private var delegate: CurrencySwitchDelegate? { 
    return self.outletDelegate as! CurrencySwitchDelegate? 
} 
+0

感謝您的回答,也嘗試過這種方式,它的工作原理,但我不喜歡的樣板代碼 –

+0

是的,我不喜歡但這是Xcode支持它的唯一方法。另一種解決方案是使用@objc,但如果您使用它的話,由於Objective-C的兼容性,您不能在協議的方法中使用可選的...等快速特性。 –

+0

有道理。感謝您的擴展解釋! –