How to make a class conform to a protocol in Swift?

YuXuan Fu picture YuXuan Fu · Jul 28, 2014 · Viewed 48.7k times · Source

in Objective-C:

@interface CustomDataSource : NSObject <UITableViewDataSource>

@end

in Swift:

class CustomDataSource : UITableViewDataSource {

}

However, an error message will appear:

  1. Type 'CellDatasDataSource' does not conform to protocol 'NSObjectProtocol'
  2. Type 'CellDatasDataSource' does not conform to protocol 'UITableViewDataSource'

What should be the correct way ?

Answer

Alex Wayne picture Alex Wayne · Jul 28, 2014

Type 'CellDatasDataSource' does not conform to protocol 'NSObjectProtocol'

You have to make your class inherit from NSObject to conform to the NSObjectProtocol. Vanilla Swift classes do not. But many parts of UIKit expect NSObjects.

class CustomDataSource : NSObject, UITableViewDataSource {

}

But this:

Type 'CellDatasDataSource' does not conform to protocol 'UITableViewDataSource'

Is expected. You will get the error until your class implements all required methods of the protocol.

So get coding :)