Reputation: 494
I have a doubt related to protocol method and class method. below code explain the what i want to achieve,
protocol Test {
func abc()
}
class Base {
func abc() { }
}
class MyCustomClass: Base, Test {
}
So, question is which method MyCustomClass
will add ?
In my scenario, i want to add Test
protocol method as well as 'Base' class method. as of now this is allowing me to add Base
class method with 'override' keyword.
So, does anyone know how can we access both Test Protocol
and Base Class
?
Is it possible to get both method in MyCustomClass
which are containing same name of the method ?
Upvotes: 0
Views: 50
Reputation: 534950
You seem not to understand what a protocol is. It is merely a contract guaranteeing that its adopter contains certain members.
So let's look at your code, which I have modified only slightly:
protocol Test {
func abc()
}
class Base {
func abc() { print("Base abc") }
}
class MyCustomClass: Base, Test {
}
The important thing about your code is that it compiles. Why? By adopting Test, MyCustomClass promises that it contains an abc()
function. And it keeps that promise. How? By inheriting an abc()
function from its superclass, Base.
As for "what happens", just try it:
MyCustomClass().abc() // Base abc
We instantiate MyCustomClass, call that instance's abc()
, and sure enough, the abc()
inherited from Base runs, in accordance with the laws of polymorphism.
But that has nothing to do with the protocol! The protocol is irrelevant and serves no purpose here. You could delete the protocol entirely from the example and get exactly the same result. The protocol is just a description of its adopter. It says "whoever adopts me has an abc()
function," and sure enough, MyCustomClass adopts the protocol and does have an abc()
function.
Upvotes: 1