ios - Swift 通用闭包

标签 ios swift generics closures

我正在为静态 TableView 构建一个库,它工作正常,但我遇到了通用闭包的问题。

目前看起来是这样的:

orderForm = Form(tableView: orderTable) { f in
    f.section { s in
        s.footer("Při platbě nejsou účtovány žádné další poplatky.")
        s.cell("Selection")
            .configure { (cell, path) in
                let c = cell as! ProfileSelectionCell
                c.titleLabel?.text = "Způsob platby"
                c.detailLabel?.text = self.paymentType.first
            }
        s.cell("Selection")
            .configure { (cell, path) in
                let c = cell as! ProfileSelectionCell
                c.titleLabel?.text = "Balíček"
                c.detailLabel?.text = "20 kr. za 1000 Kc"
            }.selected { path in

            }
        }
    }

我想让“cell”变量已经转换为适当的类型,在本例中为 ProfileSelectionCell。

这是细胞类的来源:

class Cell {
internal let id: String
internal var configure: ((cell: UITableViewCell, path: NSIndexPath) -> Void)?
internal var selected: ((path: NSIndexPath) -> Void)?

init(id: String) {
    self.id = id
}

func configure(config: ((cell: UITableViewCell, path: NSIndexPath) -> Void)?) -> Self {
    self.configure = config
    return self
}

func selected(selected: (path: NSIndexPath) -> Void) -> Self {
    self.selected = selected
    return self
}}

我的问题是,如果我将配置方法设为通用,则无法将配置闭包存储到单元变量,如果我将整个单元设为通用,则无法将单元保存到 Section 类中的数组等等..

这有什么办法可以解决吗?

最佳答案

您可以使 Cell 类通用,例如

class Cell<T : UITableViewCell> {
}

然后使用 T 代替每个 UITableViewCell

不幸的是,您也必须在 SectionForm 类中使用相同的内容。这适用于具有一种单元格类型的表格,但它可能不适用于具有多种单元格类型的表格。在那种情况下,您将总是需要在某处转换。

关于ios - Swift 通用闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37569136/

相关文章:

c# - 将派生类的列表<>转换为基类的列表<>

java - 如何调用参数化类型的方法?

ios - 如何更改 UI 分段控件标题颜色

iOS - 移动图像时旋转图像

ios - 使单个单元格重叠

ios - HockeyApp iOS-在崩溃日志中看到未调用的方法名称

ios - Swift .isNaN 了解它是如何工作的

swift - 我不断收到 "Swift Dynamic Cast Failed"。我如何解决它?

swift - 如何在 SpriteKit 中将一个 Action 应用于多个 Sprite?

c# - 在具有开放泛型类型的 Controller 上创建操作方法