Reputation: 3443
I have a problem determining in swift the class behind a delegate. In my app there is a class called DataSource and a protocol called DataSourceDelegate usually given to Controller to manage.
Subclasses of DataSource can be from a single source or if they contain multiple DataSource instance they must conform to DataSourceDelegate.
DataSource does not conform to DataSourceDelegate but some of its subclasses do. So in order to determine the root data source I check for the delegate's class. If the delegate is not a DataSource or any of its subclasses it returns true.
Code:
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
}
The problem is that the if statement throws a compilation error saying: Type 'DataSource' does not conform to protocol 'DataSourceDelegate'. Is there any other way to check this?
Thanks in advance
Upvotes: 2
Views: 1254
Reputation: 122449
For what it's worth, this works:
if (dataSource.delegate as AnyObject?) is DataSource
Upvotes: 2