Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional methods in Swift protocol and overloading

Is there way to override optional methods in Swift protocol?

protocol Protocol {

    func requiredMethod()
}

extension Protocol {

    func optionalMethod() {
        // do stuff
    }
}
class A: Protocol {
    func requiredMethod() {
        print("implementation in A class")
    }
}
class B: A {
    func optionalMethod() { // <-- Why `override` statement is not required?
        print("AAA")
    }
}

Why in UIKit there is similar example?

protocol UITableViewDelegate : NSObjectProtocol, UIScrollViewDelegate {
// ......
optional public func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
}


class MyTVC: UITableViewController {
    override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{}

override statement is required!!! But UITableViewController does not respond to selector "tableView: estimatedHeightForRowAtIndexPath:"

What is problem?

like image 968
iOS User Avatar asked Apr 21 '26 21:04

iOS User


1 Answers

UITableViewController is a class, not a protocol. In protocol you can declare method that is required by your class. Protocol extensions give you ability to write default implementation of your protocol method and then even if your class "inherit" this protocol you don't have to implement this method but you can change the default implementation.

If you write code something like this:

protocol ExampleProtocol {
    func greetings() -> String
}

extension ExampleProtocol {
    func greetings() -> String {
        return "Hello World"
    }
}

class Example : ExampleProtocol {

}

then you can see "Hello World" on your console but if you re-write this method in your class:

func greetings() -> String {
    return "Hello"
}

now you will see just "Hello". You can remove this method from your class and remove the protocol extension declaration and then you will see error: "Type Example thas not conform to protocol ExampleProtocol".

like image 130
Mr. A Avatar answered Apr 24 '26 13:04

Mr. A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!