简体   繁体   English

Swift通用闭包

[英]Swift generic closure

I'm building a library for static table views and it works fine, but I encountered a problem with generic closures. 我正在为静态表视图构建一个库,它工作正常,但我遇到了通用闭包的问题。

It looks like this so far: 到目前为止看起来像这样:

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

            }
        }
    }

I wanna have the "cell" variable already cast to appropriate type, in this case ProfileSelectionCell. 我想将“cell”变量转换为适当的类型,在本例中为ProfileSelectionCell。

Here is the source for the cell class: 以下是单元类的来源:

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
}}

My problem is that if I make the configure method generic, it is not possible to store the config closure to the cell variable and if I make the whole cell generic, I can't save the cell to an array in Section class and so on.. 我的问题是,如果我使配置方法通用,不可能将配置闭包存储到单元格变量,如果我使整个单元格通用,我不能将单元格保存到节类中的数组,依此类推..

Is this solvable in any way? 这可以解决吗?

You can make the Cell class generic, eg 您可以使Cell类通用,例如

class Cell<T : UITableViewCell> {
}

and then use T instead of every UITableViewCell . 然后使用T代替每个UITableViewCell

Unfortunately you would have to have the same in both Section and Form classes, too. 不幸的是,你也必须在SectionForm类中拥有相同的功能。 That would work for tables with one type of cells but it won't probably work for tables with multiple cell types. 这适用于具有一种类型单元格的表格,但它不适用于具有多种单元格类型的表格。 In that case you will always need casting somewhere. 在这种情况下,你总是需要在某处施放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM