Using meaningful names

Always try to choose meaningful names for your variables and constants. Good names can acts as documentation and make your code easy to read.

A good name specifically describes what the variable or constant represents. Here are some examples of good names:

  • personAge
  • numberOfPeople
  • gradePointAverage

Often a bad name is simply not descriptive enough. Here are some examples of bad names:

  • a
  • temp
  • average

The key is to ensure that you’ll understand what the variable or constant refers to when you read it again later. Don’t make the mistake of thinking you have an infallible memory! It’s common in computer programming to look back at your own code as early as a day or two later and have forgotten what it does. Make it easier for yourself by giving your variables and constants intuitive, precise names.

Also, note how the names above are written. In Swift, it is common to camel case names. For variables and constants, follow these rules to properly case your names:

  • Start with a lowercase letter.
  • If the name is made up of multiple words, join them together and start every other word with an uppercase letter.
  • If one of these words is an abbreviation, write the entire abbreviation in the same case (e.g.: sourceURL and urlDescription)

In Swift, you can even use the full range of Unicode characters. For example, you could declare a variable like so:

That might make you laugh, but use caution with special characters like these. They are harder to type and therefore may end up causing you more pain than amusement.

Special characters like these probably make more sense in data that you store

rather than in Swift code; you’ll learn more about Unicode in Chapter 4, “Strings.”

results matching ""

    No results matching ""