I am doing some test projects to learn Swift, and there is a compilation problem that I cannot solve.
I defined a protocol like this:
@objc protocol MyDataProvider : UICollectionViewDataSource, UICollectionViewDelegate, NSObjectProtocol {
var myData : AnyObject { get }
}
and the class implementing it:
class MyData : NSObject, MyDataProvider {
var myData:AnyObject
init() {
self.myData = Int()
}
func collectionView(collectionView: UICollectionView!, numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell! {
return nil
}
}
I can create an instance of this class and refer to it through a protocol variable:
let dataProvider : MyDataProvider = MyData()
Next, I want to use this instance in the view controller:
class MyController : UIViewController {
let dataProvider : MyDataProvider = MyData()
@IBOutlet var collectionView : UICollectionView
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.dataSource = dataProvider
self.collectionView.delegate = dataProvider
}
}
The last 2 assignments are reported by the compiler as errors, with the following error message:
Type 'MyDataProvider' does not conform to protocol 'NSObjectProtocol'
If I do not use the interface and declare the property as a class type:
let dataProvider = MyDate()
it compiles. So there MyDataProvidershould be something wrong with the protocol , I just can’t understand that.
If I delete one of the two delegates implemented by the interface, after commenting the corresponding line into viewDidLoad()compilation, it still fails. But if I remove NSObjectProtocolfrom the protocol:
protocol MyDataProvider : UICollectionViewDelegate {
var myData : AnyObject { get }
}
compilation now succeeds. So, it UICollectionViewDelegateimplements NSObjectProtocol, therefore, it seems that the protocol cannot implement another protocol more than once, directly or indirectly. But if I remove NSObjectProtocolfrom the interface and leave two delegates to view the collection:
protocol MyDataProvider : UICollectionViewDataSource, UICollectionViewDelegate {
var myData : AnyObject { get }
}
Compilationstill not running because both implement NSObjectProtocol. How to solve this?