我一直在嘗試做一些代碼,允許用戶「附加」到特定單元格的特定模型。我打算通過協議和associatedType
方法來做到這一點。如何在Swift中測試與associatedType協議的一致性?
這裏的計劃:
細胞符合MTZSectionRowConfigurable
時,他們可以顯示數據,但他們不一定需要:
public protocol MTZSectionRowConfigurable {
associatedtype T: MTZSectionRowModel
func configure(with model: T?)
}
通過使用typealias
,它們允許用戶定義哪種模式他們「再要代表:
class SignOutCell: UITableViewCell, MTZSectionRowConfigurable {
typealias T = SignOutModel
var redLabel: UILabel!
// ...
func configure(with model: SignOutCellModel?) {
self.redLabel.text = model?.text
}
}
模型只是順應MTZSectionRowModel
明確聲明補償atibility。
但是,由於表示模型是可選的,我需要在調用configure方法之前檢查單元以支持它們。這是對cellForRowAtIndexPath:
if let cell = cell as? MTZSectionRowConfigurable {
cell.configure(with: sectionRow.model)
}
完成。在上述例子中,是sectionRow.model
MTZSectionRowModel?
類型。
以上代碼不能編譯。它產生臭名昭著:
「協議‘MTZSectionRowConfigurable’只能作爲一種通用的約束,因爲它具有自我或相關類型的要求」
我試圖檢查電池也迴應#selector
,但不幸的是,同樣的錯誤適用。
有什麼辦法可以使這段代碼有效嗎?我錯過了什麼嗎?我可以放棄associatedType
,在每個單元格上實施廣泛的方法MTZSectionRowModel
,但是然後我需要在每個實現內部施放,但在我看來這不是最佳解決方案。