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()
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.
Java static code analysis: "Optional" should not be used for parameters.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With