我撰寫了一個擴展來輕松地使某種型別的表格視圖單元格出列:
class RedCell: UITableViewCell { }
class BlueCell: UITableViewCell { }
extension UITableView {
func dequeueReusableCell<T: UITableViewCell>(_ type: T.Type, for indexPath: IndexPath) -> T {
let identifier = String(describing: T.self) // Must set on Storyboard
return dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! T
}
}
這使得正確型別的單元格出列非常容易:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(RedCell.self, for: indexPath) // type: RedCell
}
現在,RedCell.self我不想輸入該函式呼叫,而是將其存盤SomeCell.self在一個變數中,以便每個列舉案例都可以將它們自己的自定義單元格子類傳遞給表視圖:
enum Color {
case red, blue
// ...?
// func cellType<T: UITableViewCell>() -> T.Type {
// func cellType<T>() -> T.Type where T: UITableViewCell {
func cellType<T>() -> T.Type {
switch self {
case .red: return RedCell.self // Cannot convert return expression of type 'RedCell.Type' to return type 'T.Type'
case .blue: return BlueCell.self // Cannot convert return expression of type 'BlueCell.Type' to return type 'T.Type'
}
}
}
期望的結果是通過列舉案例構造單元格:
let color = Color.red
let cell = tableView.dequeueReusableCell(color.cellType(), for: indexPath) // type: UITableViewCell
可以將上述呼叫的回傳型別向上轉換為 in-common UITableViewCell,而不是子類。但是cellType()應該從 Storyboard 中出列正確的單元子類,如第一個代碼塊所示,它基于類名的字串。
這可能嗎?Xcode 為我嘗試撰寫函式提供了上述錯誤。
What is the correct syntax for the generic function I'm attempting to write?
uj5u.com熱心網友回復:
不需要泛型;只需回傳UITableViewCell.Type:
enum Color {
case red, blue
func cellType() -> UITableViewCell.Type {
switch self {
case .red: return RedCell.self
case .blue: return BlueCell.self
}
}
}
uj5u.com熱心網友回復:
我不確定我是這個想法的粉絲,但看看這個,只需使用私有靜態變數并將其設定為所需的型別。
這樣您就可以避免從 return 陳述句推斷錯誤,并且仍然根據您的列舉情況更改型別。
enum Color {
private static var cellType = UITableViewCell.self
case red, blue
private func setCellType(){
switch self{
case .red:
Color.cellType = RedCell.self
case .blue:
Color.cellType = BlueCell.self
}
}
func cellType<T: UITableViewCell>() -> T.Type {
setCellType()
return Color.cellType as! T.Type
}
}
class Test {
init(){
print(String(describing: Color.red.cellType()))
}
}
let test = Test()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/335390.html
標籤:ios swift uitableview generics
上一篇:在有條件的行上聚合列
下一篇:迭代陣列串列以用作函式中的輸入
