[swift-evolution] [proposal] Allow function argument type to be omitted when passing a default value from which it can be inferred

Sam Dods sam at theappbusiness.com
Tue May 10 05:02:44 CDT 2016


I propose that function argument types could be omitted in the same way as variable and property argument types are omitted when they are set at point of definition.

At present the type of properties and variables can be inferred as below:

class EvolutionManager {
  let proposalManager = ProposalManager()           // type is inferred

  func proposeTopic(topic: String) {
    let evolution = Evolution(topic: topic)         // type is inferred
    proposalManager.proposeEvolution(evolution)
  }
}

However, function arguments cannot be inferred, as below:

class EvolutionManager {
  func proposeEvolution(evolution: Evolution, proposalManager = ProposalManager()) {       // compiler error, cannot infer type
    proposalManager.proposeEvolution(evolution)
  }
}

It's a nice feature of the language that the type can be inferred for properties and variables, so I don't see any reason not to allow the same for function arguments. It allows for more concise code, and adds consistency with other language features. And I don't personally think it would make our code any harder to read.

There are of course some cases where the type cannot be inferred, i.e. when the type should actually be a protocol type and the default value is a concrete type. Consider the following:

protocol ProposalHandler {
  associatedType P : Proposable
  propose(p: P)
}

class EvolutionManager {
  // the type would be inferred as the concrete type `ProposalManager` and could not be
  // called with any other argument type that conforms to the `ProposalHandler` protocol,
  // as may have been the intention
  func proposeEvolution(evolution: Evolution, proposalHandler = ProposalManager())

  // instead it should be written as follows:
  func proposeEvolution(evolution: Evolution, proposalHandler: ProposalHandler = ProposalManager())
}

But this is the same for properties and variables, so it should not be a reason to not allow inferring of function arguments. For example:

class EvolutionManager {
  // the property is inferred as the concrete type `ProposalManager` and may not
  // be set to any other value of type that conforms to the `ProposalHandler` protocol,
  // as may have been the intention.
  var proposalHandler = ProposalManager()

  // instead it should be written as follows:
  var proposalHandler: ProposalHandler = ProposalManager()
}

What do people think of this?

It would have no impact on existing code, and it's not the kind of thing that needs an alternative solution.




More information about the swift-evolution mailing list