Can I support multiple inheritance using protocol in swift?

In Swift, using the extension, you can provide the body of the method in a "protocol". in my code, I can give the body of the method, see

protocol Test1{
    func display()
}
extension Test1{

    func display(){
        print("display Test1")
    }
}

protocol Test2{
    func display()
}
extension Test2{

    func display(){
        print("display Test2")
    }
}
class ViewController: UIViewController,Test1,Test2 {

    var test1 : Test1?
    var test2 : Test2?

    func display() {
        print("display")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.test1 = self
        test1?.display()

        self.test2 = self
        test2?.display()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

I know that I give the address of the object test1 and test2 in the ViewController class. therefore, the “display” is printed twice. but in both "protocols" I can combine these methods.

so my question is why does Apple give me functionality to write the body of methods in a "protocol"?

Can someone help me understand this functionality?

+3
source share
1 answer

, , , , , :)

, , - , JAVA, Objective-C - DiamondProblem

, / , ( Objective C), , Inheritance!!, , , super.methodname??? , ??? ?

, Protocols - , , .

: , , , , , , :) , ' t !!!

, , , . , - :)

protocol Test {
    func test1()
}

extension Test {
    func test1() {
        print("Yo man")
    }
}

protocol Test2 {
    func test2()
}

extension Test2 {
    func test2() {
        print("Bye man")
    }
}

class ViewController: UIViewController,Test,Test2 {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.test1()
        self.test2()
    }
}

, test1 test2, , :)

. , .

:

: Test1 Test2 , DiamondProblem, display(), ? 1 2?? Swift , display() self.display()

, , , ur, test1 test2, , test1.display() test2.display(), , thats , , ?

, Diamond :)

+4

Source: https://habr.com/ru/post/1685019/


All Articles