我遇到了使用泛型的問題。Swift通用返回結構體
我有一個協議:SectionReusableView
public protocol SectionReusableView {
associatedtype AdapterType: SectionReusableViewAdapter
var adapter: AdapterType? { get set }
}
我有這樣的結構TableViewSectionReusableSupplementraryViewFactory
public struct TableViewSectionReusableSupplementraryViewFactory<T: SectionReusableView> {
public var adapter: T.AdapterType
public init(adapter: T.AdapterType) {
self.adapter = adapter
}
}
我要的是創造這將返回任何TableViewSectionReusableSupplementraryViewFactory
指定類型的功能T
func supplementaryViewFactory<T>(at index: Int,
within tableView: UITableView) -> TableViewSectionReusableSupplementraryViewFactory<T>? {
let adapter = self.adapter(at: index, within: tableView)
let reuseIdentifier = self.reuseIdentifier(at: index)
switch reuseIdentifier {
case AwesomeReusableView.AwesomeReusableViewReuseIdentifier:
guard let adapter = adapter as? AwesomeReusableViewAdapter else { return nil }
return TableViewSectionReusableSupplementraryViewFactory<AwesomeReusableView>(adapter: adapter)
default:
return nil
}
}
,但我得到這個錯誤,我不知道如何繞過
error: cannot convert return expression of type
'TableViewSectionReusableSupplementraryViewFactory<AwesomeReusableView>' to return
type 'TableViewSectionReusableSupplementraryViewFactory<T>?'
謝謝:)但我不能這樣做,調用補充的ViewFactory的類不知道哪個類型要專門化。 這就是爲什麼我想返回一個「任何」TableViewSectionReusableSupplementaryViewFactory – Pwyll28
@ Pwyll28,我認爲,在這種情況下,我會建議從泛型轉向,只使用普通的jane協議。或者,如果您想保留泛型,請讓您的主結構實現一個協議,然後將其作爲工廠方法的返回類型,並從中刪除「」 –
utahwithak
但此方法的要點是返回的工廠或或並使用工廠在另一個類中實現我的UITableViewDelegate/Datasource方法@utahwithak –
Pwyll28