Hello everyone. Because there is no "virtual" keyword I don't know that how can I create a subclass which has 2 methods with 2 rule for each one:
- First method:
- If object was created from its own class, it has to call its own method.
- If there is an upcasting, it has to call the base class's method
- Second method:
- If object created from its own class, it has to call its own method.
- If there is an upcasting, it has to call its own method again.
Let me explain with c# code
// <BEGIN_IMPORTANT_PART>
Console.WriteLine("From base_derived");
Base base_derived = new Derived();
base_derived.ifPolyCallBase(); // nonOverridedFromBase
base_derived.ifPolyCallDerived(); // overridedFromDerived
// <END_IMPORTANT_PART>
Console.WriteLine("\nFrom base");
Base @base = new Base();
@base.ifPolyCallBase(); // nonOverridedFromBase
@base.ifPolyCallDerived(); // overridedFromBase
Console.WriteLine("\nFrom derived");
Derived derived = new Derived();
derived.ifPolyCallBase(); // nonOverridedFromDerived
derived.ifPolyCallDerived(); // overridedFromDerived
class Base
{
virtual public void ifPolyCallBase()
{
Console.WriteLine("nonOverridedFromBase");
}
virtual public void ifPolyCallDerived()
{
Console.WriteLine("overridedFromBase");
}
}
class Derived : Base
{
public void ifPolyCallBase()
{
Console.WriteLine("nonOverridedFromDerived");
}
override public void ifPolyCallDerived()
{
Console.WriteLine("overridedFromDerived");
}
}
In swift when i use override it calls only derived method, we cannot use without override too, and i cannot delete the method too because of other functionalities as you see. So my questions are:
What is the equivalent code in swift (you can use protocol-struct instead of classes if it is preferable)
If there is no "virtual" keyword, I think there is a good reason, could you explain why?
With closest swift code I tried to explain what I want. Is there any way to change first output without change other ones.
class Base {
func ifPolyCallBase() {
print("FromBase")
}
func ifPolyCallDerived() {
print("FromBase")
}
}
class Derived: Base {
override func ifPolyCallBase() {
print("FromDerived")
}
override func ifPolyCallDerived() {
print("FromDerived")
}
}
let base_derived: Base = Derived()
base_derived.ifPolyCallBase() // FromDerived (PROBLEM: But I want to see output "FromBase" without change other outputs)
base_derived.ifPolyCallDerived() // FromDerived
let base: Base = Base()
base.ifPolyCallBase() // FromBase
base.ifPolyCallDerived() // FromBase
let derived: Derived = Derived()
derived.ifPolyCallBase() // FromDerived
derived.ifPolyCallDerived() // FromDerived
Thanks!