Mastering Swift
上QQ阅读APP看书,第一时间看更新

Constants and variables

Constants and variables associate an identifier (such as myName or currentTemperature) with a value of a particular type (such as a String or Int) where the identifier can be used to retrieve the value. The difference between a constant and a variable is that a variable can be updated/changed while a constant cannot be.

Constants are good for defining values that you know will never change, such as the freezing temperature of water or the speed of light. Constants are also good for defining a value that we use many times throughout our application, such as a standard font size or maximum characters in a buffer. There will be numerous examples of constants throughout this book.

Variables are more common in software development than constants. You can make useful applications without using constants (although it is a good practice to use constants); however, it is almost impossible to create a useful application without variables.

You can use almost any character in the identifier of a variable or constant (even Unicode characters); however, there are a few rules that you must follow, they are as follows:

  • An identifier must not contain any whitespace
  • An identifier must not contain any mathematical symbols
  • An identifier must not contain any arrows
  • An identifier must not contain private use or invalid Unicode characters
  • An identifier must not contain line or box drawing characters
  • An identifier must not start with a number, but they can contain numbers
  • If you use a Swift keyword as an identifier, surround it with back ticks
    Note

    You should avoid using Swift keywords as identifiers.