From page 6 on in The Swift Language, it is clear that the language designers pride themselves on the fact that while Swift is strongly typed, programmers often don't have to worry about types, because they are inferred from context.
I find it odd, therefore, that explicit types are required even when default parameter values make the parameter types clear.
For example, String is required in this declaration:
func assign(motto: String = "Winter is coming") { /* ... */ }
even though the type of motto is clear here:
func assign(motto = "Winter is coming") { /* ... */ }
and is easier to read than the legal code.
Do you know or can you imagine why this is?
I could find no change requests in Evolution in this area. (https://apple.github.io/swift-evolution)
One investigation
My first thought was that allowing programmers to omit parameter types would allow them to build complex types within parameter declarations that could be difficult to read:
func update(inventory = [
("Daenerys", ("dragons", -1)),
("Cersei", ("children", -3))
]) {
/* ... */
}
But that danger doesn't bother the language designers in variable declarations. This is legal Swift:
var houseData = [
["Stark": ["Sigil": "Dyer Wolf", "Motto": "Winter is coming"]],
["Lannister": [
"Sigil": "Lion",
"Motto": "Hear me roar",
"Saying": "A Lannister pays his debts"
]]
]
One reason might be to make the lives of the people who read your code easier.
Let's say I am reading your code and I saw
func foo(param = bar.baz) {
It would take me a second to realise what type param is. I need to go to the definition of bar.baz and see what type that is.
Unlike a variable declaration, the type of a parameter is much more important because users of your method need to know the type, so that they know what to pass to your method.
Also, making parameter types required also makes the spec simpler to write. There is only one case:

Otherwise there would be two cases: one with an optional type annotation, and another one with an optional default argument clause.
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