【问题标题】:Determining class of delegate property in swift快速确定委托属性的类别
【发布时间】:2014-08-12 01:54:54
【问题描述】:

我在快速确定代表背后的班级时遇到问题。在我的应用中,有一个名为 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' does not conform to protocol 'DataSourceDelegate'。还有其他方法可以检查吗?

提前致谢

【问题讨论】:

  • 你的代码第一行出现错误:protocol DataSourceDelegate: class
  • 是的,但它产生的错误是无法理解的。
  • @hlfcoding:不。这是 Xcode 6 beta 5 中用于声明纯类协议的正确语法。
  • 请注意,在开发过程中,您可以简单地print(thatDelegateVariable),它会通过名称告诉您它是哪个类。

标签: ios delegates swift


【解决方案1】:

对于它的价值,这是有效的:

if (dataSource.delegate as AnyObject?) is DataSource

【讨论】:

  • 完美运行,非常感谢。如果 Apple 能够以某种方式减少 is 运算符的限制,那就太棒了。
猜你喜欢
  • 2023-03-12
  • 2015-10-25
  • 2016-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多