I need to make a class conform to a protocol in Swift in order to implement a delegate. How would I do so?
Protocols allow you to group similar methods, functions, and properties. Swift lets you specify these interface guarantees on class , struct , and enum types. Only class types can use base classes and inheritance from a protocol.
It is just described as a methods or properties skeleton instead of implementation. Methods and properties implementation can further be done by defining classes, functions and enumerations. Conformance of a protocol is defined as the methods or properties satisfying the requirements of the protocol.
Mitrenegades solution is to use an objective-c protocol, is one way, but if you want a swift protocol, then the other would be to refactor the code so as to not use the objective-c class directly, but instead use the protocol (e.g. some protocol based factory pattern). Either way may be appropriate for your purposes.
You can create objects from classes, whereas protocols are just type definitions. Try to think of protocols as being abstract definitions, whereas classes and structs are real things you can create.
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).
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With