Vs Protocol Class Inheritance

I got a little confused with the following concept:

Code 1:

class New{
    func abc(){
        print("new class")
    }
}

class ClassNew: New {
    override func abc() {
        print("derived class")
    }
}

Code 2:

protocol New{}

extension New{
    func abc(){
        print("new protocol")
    }
}

class ClassNew: New {
    func abc() {
        print("derived protocol")
    }
}
  • What is the difference between Code 1and Code 2since they both fulfill the same goal?

  • Q Code 2, classNewis there a inheritingnew protocol or just conforminga protocol?

Any explanation would be much appreciated!

+4
source share
4 answers

Code 1 and code 2 basically do not match .

What is the difference between code 1 and code 2, since they both fulfill the same goal?

No, they do not. The first defines the class hierarchy, the second defines the protocol (API, if you want) and the type corresponding to it.

2 New ?

. ( ).


1 , . abc(), , , i.e.

let x: New = ClassNew()
let y: ClassNew = ClassNew()

print(x.abc()) // prints "derived class"
print(y.abc()) // prints "derived class"

abc()

2 . , " ", . , , , , . ( ) , abc()

protocol New2{}

extension New2{
    func abc(){
        print("new protocol")
    }
}

class ClassNew2: New2 {
    func abc() {
        print("derived protocol")
    }
}

let y2: ClassNew2 = ClassNew2()
let x2: New2 = y2

print(x2.abc()) // prints "new protocol"
print(y2.abc()) // prints "derived protocol"

x2 y2 , . , - x2, , . , abc(), .

:

protocol New3{
    func abc()
}

extension New3{
    func abc(){
        print("new protocol")
    }
}

class ClassNew3: New3 {
    func abc() {
        print("derived protocol")
    }
}

let y3: ClassNew3 = ClassNew3()
let x3: New3 = y3

print(x3.abc())  // prints "derived protocol"
print(y3.abc())  // prints "derived protocol"

, abc() , . .

+4

classNew . Swift, .

: , , , , .

+1

Code 1 Code 2 , .

, Class , Protocol .

Java, a Protocol Interfaces.

+1

2 . , super.abc() Code 2 - , - super.

It’s just my opinion - do not use the default implementation of the protocol, since the compiler will not save you if you forget to provide "override" when you really need it.

+1
source

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


All Articles