20

I need to make a class conform to a protocol in Swift in order to implement a delegate. How would I do so?

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Phillip
  • 1,205
  • 3
  • 15
  • 22

2 Answers2

43
class YourClass: SuperClassIfAny, FirstProtocol, SecondProtocol {
}

Note, though, that some protocols require you to implement delegate methods. For instance, UITableViewDataSource requires you to implement

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int

and

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!

If those are not implemented by the class conforming to the protocol, Xcode will give you a compile error (always check the protocol declaration, Cmd + Click will show you what methods you must implement).

Oscar Swanros
  • 19,767
  • 5
  • 32
  • 48
  • 1
    Wish it would show a more useful error than: 'does not conform to protocol' – Adam Waite Jun 10 '14 at 13:06
  • Agree, I actually spent some time trying to find why it wasn't compiling. I think this is a good thing, though, prevents you from stupid errors. It'd be cool if they added a more descriptive error, still :-P – Oscar Swanros Jun 10 '14 at 16:21
1

Xcode 6 beta 7 changed the protocol slightly for UITableViewDataSource to match the following syntax on the two required implementations:

6b7 : UITableViewDataSource

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell!

compared to 6b6

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell

Of key difference is that UITableView, NSIndexPath and UITableViewCell are no longer 'Implicitly Unwrapped Optionals'

Community
  • 1
  • 1