[edited 2023-09-27 07:36 based on @ktoso's comments below]
Scala has the concept of implicit values. When I first came across this, I was horrified by what I saw as an overly magical and opaque language feature. It's taken me awhile, but I've come to really appreciate it, especially when it comes to injecting mockable dependencies.
I'm imagining a similar concept in Swift, where the most recent in-scope value will automatically be passed in to implicit functions.
func foo(bar: Int, baz: implicit String) {
print(1, baz)
}
implicit let baz = "hello"
foo(bar: 1) // "1 hello"
protocol Assistant {
func doTheThing()
}
final class ViewModel {
func doTheThing(assistant: some implicit Assistant) {
assistant.doTheThing()
}
}
struct ZhuLi: Assistant {
var season: Int
func doTheThing() {
print(season < 4 ? "Yes sir" : "No, Varrick")
}
}
implicit let assistant = ZhuLi(season: 4)
let viewModel = ViewModel()
viewModel.doTheThing() // "No, Varrick"
This could make dependency injection a whole lot easier.
I don't currently have the skills to implement anything like this, but I wanted to get folks' thoughts on it (and maybe poke the curiosity of someone who might have more experience than me ).