TL ; DR:
-
In Swift, we use the camelCase convention to name our variables. It implies separating different words with capital letters, like this:
let companyName = "Apple" let foundingYear = 1976 let isUnicorn = true let numberOfEmployees = 137000
Full lesson:
Variable names must consist ONLY of letters, numbers and underscores and they must start with a letter or underscore.
Bad variable names:
let 18spam: Int
let x.15: String
let #name: Bool
If you try to create a variable with any of these names, Swift will throw an error.
Naming conventions: camelCase and snake_case
Sometimes a variable name might consist of multiple words, for example if you want to store the first name of a person. You might be tempted to separate those names by whitespaces, like this:
let first name = "Kate"
This code will also throw an error.
When you name your variables, you want to use one of these two conventions:
snake_case = separate different words with an underscore (_), like this:
let first_name = "Jane"
let last_name = "Doe"
camelCase = separate different words with capital letters, like this:
let firstName = "Jane"
let lastName = "Doe"
It's important to be consistent with the casing technique you use. Do not combine both of them in the same code, like this:
let first_name = "Jane"
let lastName = "Doe"
Case sensitive:
Variable names are case sensitive:
let name = "Kate"
let Name = "Andy"
let NAME = "George"
print(name, Name, NAME) // Output: Kate Andy George
Although Swift allows us to do this, it's always confusing and a bad coding practice to differentiate variable names just by case!
Mnemonic Variable Names:
Since we programmers are given a choice in how we choose our variable names, there is a bit of "best practice".
Sometimes we want them short like x and y, but sometimes we want them descriptive, especially if they are important.
Here is a great example:
let a = 25
let b = 13
let c = a * b
print(c)
compared to:
let hours = 25
let rate = 13
let pay = hours * rate
print(pay)
Swift understands and is happy with both of these pieces of code. But it's clearly which version makes your reader happier.
Assignment
Follow the Coding Tutorial and let's let's name some variables well!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.