I personally see no good reason why this rule should only apply to struct
types, though I did miss that no init(_, _)
had been defined originally for Point
; I’ve updated my post appropriately.
Even with this kind of shorthand, I think that argument labels would need to be kept as usual when eliding the .init
. Not requiring this could lead to serious ambiguities for initializers overloaded on argument labels, of which there are a lot, and in general I think Swift’s labeling is a Good Thing™. If someone wants their type to be initialized by a tuple without argument labels, they should be required to provide an appropriate initializer.
Thinking about how this could be generalized to non-tuples as well, I’ve arrived at the following C++ inspired idea:
The Idea
What if we added a new keyword, implicit
, that could prefix an initializer? For instance:
struct Point {
let x: Int
let y: Int
implicit init(_ x: Int, _ y: Int) { ... }
}
For initializers taking multiple parameters, an implicit
qualifier would allow the aforementioned elision of the .init
, allowing direct initialization from a tuple literal. For unlabeled initializers taking one parameter of type T
, an implicit initialization could be performed from any T
(basically implicit casts).
Even more interestingly, we could allow the implicit
prefix on enum cases:
enum JSONValue {
case null
implicit case number(Double)
implicit case string(String)
...
}
// This would be valid (interpreted as a .number(4) instance):
let foo: JSONValue = 4
This would also allow the automatic conversion from T
to T?
, which is currently one of the magical aspects of Optional
, to be done through a basic language feature.