官术网_书友最值得收藏!

The differences between variables and constants

Probably, the most often used feature in all programming languages is creating and storing a value. We create local variables in functions and declare them in classes and other data structures; that's why it's very important to do it properly.

In Swift, there are two ways of creating and storing a value, as follows:

  • Making it a variable:
    var name = "Sara"
  • Making it a constant:
    let name = "Sara"

The difference between variables and constants is that a constant value can be assigned only once and can't be changed after that. A variable value, on the other hand, can be changed anytime. Here's an example:

var name = "Sam"
name = "Jon"

let lastName = "Peterson"
lastName = "Jakson" //Error, can't change constant after assigning

Tip

The golden rule is to always declare your type as a constant (the let keyword in the previous example) first. Change it to a variable (the var keyword) only if you need it afterwards.

There are some exceptions when you can't declare it as a constant, for example, when making @IBOutles or weak. Also, optional values must be declared as variables.

Using constants has many benefits over using variables. A constant is an immutable type, and we will cover all the benefits of immutability later. The two most important benefits are as follows:

  • Safety (protection from unexpected value changes)
  • Better performance

You should use constants both when declaring properties and as local constants in functions. We should apply this rule and change our Person and JournalEntry classes as follows:

class Person {
  let name: String
  let lastName: String
...
}

class JournalEntry {
  let title: String
  let text: String
  let date: NSDate
...
}

Usually, you will find yourself using constants more often than variables. Let's look at an example where you could think about using a variable but, in fact, a constant would be a better solution. Let's say you have created a new person in the application and now you want to display a full name with a gender prefix:

let person = Person(firstName: "Jon", lastName: "Bosh")
let man = true

var fullName: String
if man {
  fullName = "Mr "
} else {
  fullName = "Mrs "
}

fullName += person.firstName
fullName += " "
fullName += person.lastName

If you think a bit more about the problem, you will realize that fullName of the person should be immutable; it's not going to change, and it should be declared as a constant:

let person = Person(firstName: "Jon", lastName: "Bosh")
let man = true

let gender: String = man ? "Mr": "Mrs"
let fullName = "\(gender) \(person.firstName) \(person.lastName)"
主站蜘蛛池模板: 苍梧县| 邵阳县| 嘉禾县| 佛冈县| 桐乡市| 确山县| 安康市| 罗甸县| 古蔺县| 鄂伦春自治旗| 乐山市| 台安县| 滁州市| 鹰潭市| 汉中市| 闽侯县| 来凤县| 南陵县| 静宁县| 武定县| 江永县| 彭水| 阿克苏市| 尼玛县| 定南县| 黑河市| 尉犁县| 闵行区| 横峰县| 临洮县| 岗巴县| 同心县| 乌拉特后旗| 安化县| 怀宁县| 农安县| 锦州市| 达拉特旗| 大厂| 通山县| 郧西县|