Another technique is to store the default parameters as properties. Both the multiple methods and calculated property methods are shown in the example below.
class Parent {
// Programmer writes.
func doSomething(s: String = "parent", i: Int = 0) -> (String, Int) { return (s, i) }
// 2^default functions.
func doSomething2(_ s: String, _ i: Int) -> (String, Int) { return (s, i) }
@inline(__always) func doSomething2(_ s: String) -> (String, Int) { return doSomething2(s, 0) }
@inline(__always) func doSomething2(_ i: Int) -> (String, Int) { return doSomething2("parent", i) }
@inline(__always) func doSomething2() -> (String, Int) { return doSomething2("parent", 0) }
// Default properties.
var doSomething3s: String { return "parent" }
var doSomething3i: Int { return 0 }
func doSomething3(_ s: String, _ i: Int) -> (String, Int) { return (s, i) }
}
final class Child : Parent {
// Programmer writes.
override func doSomething(s: String = "child", i: Int = 1) -> (String, Int) { return (s, i) }
// 2^default functions.
override func doSomething2(_ s: String, _ i: Int) -> (String, Int) { return (s, i) }
@inline(__always) override func doSomething2(_ s: String) -> (String, Int) { return doSomething2(s, 1) }
@inline(__always) override func doSomething2(_ i: Int) -> (String, Int) { return doSomething2("child", i) }
@inline(__always) override func doSomething2() -> (String, Int) { return doSomething2("child", 1) }
// Default properties.
override var doSomething3s: String { return "child" }
override var doSomething3i: Int { return 1 }
override func doSomething3(_ s: String, _ i: Int) -> (String, Int) { return (s, i) }
}
let p: Parent = Child()
print(p.doSomething()) // ("parent", 0) :(
print(p.doSomething2()) // ("child", 1) :)
print(p.doSomething3(p.doSomething3s, p.doSomething3i)) // ("child", 1) :)
The calculated property method (3 in code above) is the technique that Scala uses. For static methods and inits the calculated properties would be static.
PS1: @Nobody1707 raised the issue of file and line directives, I am unsure how these are implemented in the compiler and therefore could comment on if they would work with any of these techniques.
PS2: As @Slava_Pestov said you can only inline for structs, enums, and final classes, but it is probably still worth adding the inline annotations as shown in the code above for the cases were it can be used.