Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Creating constants

Course details | Welcome | Welcome добро пожаловать | What you should know | What you should know Что вы должны знать | The structure of Swift | The structure of Swift Структура Swift | Writing Swift in playgrounds | Writing Swift in playgrounds Написание Свифт на игровых площадках | Declaring variables |


Читайте также:
  1. Creating a Bandpass Filter
  2. Creating a New Simulation
  3. Creating a Play List by Recording a Live Beat Arrangement
  4. Creating and using arrays
  5. Creating and using arrays Создание и использование массивов
  6. Creating computed properties

 

- So, we just started using the Var keyword. I have a new playground here but here's where I try and persuade you to use a different keyword. That in Swift, we favor using the keyword Let, instead of Var when creating pieces of named data. Now hang on a second, Simon, you might think. Didn't you just say that Swift uses Var to declare every variable. Well, yes I did, and that's absolutely true. Var declares a variable and using the keyword Let we create a constant instead. It is still a piece of named data, but once it's been given a value, that value can't change, it can't vary, it is not a variable.

If I try and change it to something else, I would expect a compile error. This value needs to stay constant through the lifetime of the executing program. Other than being unable to change it, everything else about the syntax of using Var, and Let is identical. You can use one keyword or the other. Like all variables, all constants have a name, they have a specific data type. They have a value. If Swift can infer the type from the initial value, it will.

If it can't or if you prefer to be explicit, we need that type (annotationly) colon space type name after the name of the constant. It is most common to declare a constant and also set its value on the same line, and when you're using a playground, you always need to provide the value of a constant immediately. Later, when creating our own classes, it's possible to declare the constant in one location and later set its value. Perhaps, loading a value from elsewhere, external data like a file or a webservice or user input, but you can still only do it once.

Unlike a variable, once you have assigned a value to a constant you can't then change that value, any attempt to do so will cause an error. Here's the thing, some programmers might be zoning out of it, because there's nothing remarkable about constants. We can create them in most languages. There's often a keyword like const, or final, or read only we use to declare one. Constants are one of those things that a lot of programmers don't do very much. The culture that evolves around some languages means, yeah, you might be able to do them, but you just don't see them that much. You don't really think about them.

So know that in Swift, the use of constants is encouraged. They are regarded as important, and they are common placed. There is all ready a stated best practice to use Let wherever possible. First, it's a safety feature. Whatever you can lock down, whatever constraint you can put in place around you code, do it. Also, if we know that we have a bunch of values that won't change during the lifetime of the program, there are even some performance optimizations the compiler can do. Now, of course, there's nothing wrong with Var. When you have a piece of data that needs to change through the life of the program, use Var and go in all good health.

You will see a lot of constants used in Swift. If you're not in the habit of making them, make an effort to use Let for a while. It might surprise you how often your pieces of data don't need to change once they've been given a value. Now, if you've worked in Objective-C, I want to make one explicit comparison here, that might add some clarity to this. It's a common design patent in Objective-C to find two versions of a class, an Immutable or fixed version, and a Mutable or changeable one. So, we have the NS String which is fixed, and we have the NS Mutable String which is changeable.

We have the NS Array. We have the NS Mutable Array and so on. Well in Swift, we don't worry about having different versions of classes. Simply put, if you declare a String using Var, you have a Mutable String, because it's variable so you can change it. If you create a String using Let, then you have an Immutable String, it's a constant and you can't change it. As we'll see, this idea works with more complex objects like collections too. We are getting a little bit ahead of ourselves. We haven't gotten into objects yet. So, we will revisit and refine this idea later on.

Just know that the recommendation for using Let to create constants in Swift is not just for primitive simple kinds of values, it's for everything.

 

 


Дата добавления: 2015-08-20; просмотров: 101 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Declaring variables Объявление переменных| Creating constants Создание константы

mybiblioteka.su - 2015-2024 год. (0.004 сек.)