I like that train of thought. Couldn't it be even more simple? For example:
// not current Swift ahead:
// there is no global variable `defaultContext`...
// despite of this the following compiles just fine!
func foo(context: Context = defaultContext) {
}
foo(context: Context()) // ✅
foo() // 🛑 "defaultContext" variable is undefined
func test() {
var defaultConext = Context()
foo() // ✅
}
class C {
var defaultConext = Context()
func bar() {
foo() // ✅
}
}
Probably too late for Swift as that would be a breaking change, but I do like it for its simplicity and obviousness.†
† Edit: we could make a slight syntax addition to make this happen in current swift in a compatible manner, for example:
func foo(context: Context = BIKE_SHED_NAME_HERE defaultContext) {
}
BIKE_SHED_NAME_HERE modifies how the expression is being parsed hence putting it in that position near the expression. Some candidates for it: implicit
, lazy
(to reuse the keyword), execute
, evaluate
, var
. The meaning is: use this name from the "current" (at the point of use) scope.
Ditto for @wadetregaskis 's operator example:
func == (_ a: T, _ b: T, epsilon: Double = theEpsilon) { … }
a == b // 🛑 no `theEpsilon` variable defined in the current context
(==)(a, b, epsilon: 1) // ✅
func test() {
let theEpsilon = 1.0
a == b // ✅
}