在swift中确定委托属性的类

时间:2014-08-12 01:54:55

标签: ios delegates swift

我有一个问题,迅速确定代表背后的课程。在我的应用程序中,有一个名为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语句抛出了一个编译错误:Type' DataSource'不符合协议' DataSourceDelegate'。有没有其他方法来检查这个?

提前致谢

1 个答案:

答案 0 :(得分:1)

对于它的价值,这有效:

if (dataSource.delegate as AnyObject?) is DataSource
相关问题