testing protocol conformance with associated types

落爺英雄遲暮 提交于 2019-12-03 15:03:49

As the error says, you cannot cast it to Populatable here. I think the correct way is to cast it to EventRowType.

if let rowController = self.table.rowControllerAtIndex(i) as? EventRowType {

And you already tested that 'EventRowType' class conforms 'Populatable' protocol. Because if the EventRowType doesn't have function named 'populate', swift compiler says,

Type 'EventRowType' does not conform to protocol 'Populatable'

I don't think you will be able to go generic the whole way, unless possibly by using AnyObject and testing the class of the parameter in each populateWith function.

But this will work:

for (i, p) in enumerate(rowTypes) {
    if let dateRow = p as? DateRowType {
        dateRow.populateWith(data[i] as! NSDate)
    }
    else if let stringRow = p as? StringRowType {
        stringRow.populateWith(data[i] as! String)
    }
}

You will just need to expand this for every Populatable class you add.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!