我在确定代表后的 class 时遇到问题。在我的应用程序中,通常有一个名为DataSource的类和一个称为DataSourceDelegate的协议通常提供给Controller进行管理。

DataSource的子类可以来自单一来源,或者如果它们包含多个DataSource实例,则它们必须符合DataSourceDelegate。

DataSource不符合DataSourceDelegate,但其某些子类符合。因此,为了确定根数据源,我检查了委托的类。如果委托不是DataSource或其任何子类,则返回true。

码:

protocol DataSourceDelegate: class {

}

class DataSource {

  var delegate: DataSourceDelegate?

}

class BasicDataSource: DataSource {

}

class ComposedDataSource: DataSource, DataSourceDelegate {

}

class SegmentedDataSource: DataSource, DataSourceDelegate {

}

class DataSourceManager: DataSourceDelegate {

}

let dataSourceManager = DataSourceManager()
let composedDataSource = ComposedDataSource()
let dataSource = DataSource()
dataSource.delegate = composedDataSource // dataSource is not root
composedDataSource.delegate = dataSourceManager // composedDataSource is root


if dataSource.delegate is DataSource {
  //It is not a root data source
} else {
  //It is a root data source
}

问题是if语句引发编译错误,提示:类型'DataSource'不符合协议'DataSourceDelegate'。还有其他方法可以检查吗?

提前致谢

最佳答案

对于它的价值,这可行:

if (dataSource.delegate as AnyObject?) is DataSource

10-08 05:54