May 27, 2017:  ~ 1 min read

Naming init parameters

I used to name them by the type of the parameters passed in, for example:

let dictionary = ["name": "Sneakers", "price": "40"]
let product = Product(dictionary: dictionary)
let viewModel = ProductViewModel(product: product)

But lately, I've been using a more Swifty approach, by having an external name of from or with:

let dictionary = ["name": "Sneakers", "price": "40"]
let product = Product(from: dictionary)
let viewModel = ProductViewModel(with: product)

How do I pick between the two? I go with the following approach:

  • if the object relies entirely on the parameter, I use from
  • if the object has other properties, independent on the parameter, I use with

In our example above, the product is a model, and models are usually created entirely from a dictionary (a JSON), while the viewModel might have other properties, like numberOfSections & numberOfRows for a tableView or buttonTitle - "Buy" or "Sold Out", for example.

Is the difference too subtle and not worth stressing over? Or does it slightly improve the semantic? Let me know what you think @rolandleth.

Subscribe to my monthly newsletter.
No spam, unsubscribe at any time.