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())
print(y3.abc())
, abc() , . .