Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this method with an optional parameter not override the base class method?

Tags:

swift

The result is "a", but I want it to be "b". I want to know why, and how I can call doTest without arguments to print "b".

class AA {
    func doTest() {
        print("a")
    }
}

class BB: AA {
    func doTest(_ different: Bool = true) {
        print("b")
    }
}

let bObjc = BB()
bObjc.doTest()
like image 367
cadaverousblue Avatar asked Jun 19 '19 09:06

cadaverousblue


People also ask

Why not use optional parameters?

One of the biggest misuses of optional parameters is that of providing a default argument to a function. Although it is mandatory to provide a default value to an optional argument, it doesn't mean that this feature should be used whenever you want to have some default value in a function.

Can Optional be used as a parameter in java?

Java static code analysis: "Optional" should not be used for parameters.

Why should java 8's Optional not be used in arguments?

It is part of the Java standard. It makes obvious to the reader of the code (or to the user of API), that these arguments may be null.

How do optional parameters work C#?

Optional parameters in the C# programming language allow you to specify arguments in a method signature that the caller of the method is free to omit. In other words, while you must specify values for required parameters, you might choose not to specify values for optional parameters.


1 Answers

Class BB does not override the method from AA, that means two methods exist on BB:

func doTest() // inherited
func doTest(_ different: Bool = true) // declared

When you call

bObjc.doTest()

the compiler has to choose one of them. And it prefers method without parameter over the method with a default parameter.

like image 158
Sulthan Avatar answered Sep 19 '22 22:09

Sulthan