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

Printing values and working with string interpolation. - When we're editing Swift in a playground, we can easily see the current value of any variable or constant by just writing the name of that variable or

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 | Declaring variables Объявление переменных | Creating constants |


Читайте также:
  1. Converting values
  2. Converting values Преобразование значения
  3. Gt; FROM string_tbl
  4. MY WORKING DAY
  5. My Working Day
  6. Printing values and working with string interpolation

 

- When we're editing Swift in a playground, we can easily see the current value of any variable or constant by just writing the name of that variable or constant on some line and letting the playground show the value and the results pane on the right. But we will often want to create an output of our own more interesting messages, not just single role values. In Swift, we'll use println, print l n, to do this. This is a globally available function. There is also a print function in Swift without the ln but it ends the line break at the end so this is the one we'll usually use.

All languages need something like this. It's the equivalent of printf in C, system.out.println in Java, Console.WriteLine in C-Sharp, console.log in JavaScript. Just the way of getting a message output from your program. You could use it to write out a simple string or you could write out the value of a constant or a variable but often we'll want to combine both text and the current values of variables and constants to create a more useful message. In some languages, you would use string concatenation to do this.

Often using the plus operator to concatenate various pieces of a message together with various values. Now we can do string concatenation in Swift but there is a better way for this kind of situation. In other languages, we'd use format strings or format specifiers. Say AND C or Objective-C. We define placeholders in our string with specific date and time, and following those with the variable mains meant to replace them. Well, we don't do either of these methods in Swift. Instead, we use string interpolation.

Sidebar, string interpolation might sound like a complex term but isn't. To interpolate just means to take some existing content like a sentence or a paragraph and insert some new content somewhere into it. While these days, the word interpolation is often found in programming and Mathematics, it is not just a programming term. The word interpolation has been around for a long time. Example, if you were a scholar of ancient history, studying thousand-year-old manuscripts, and then you dig up a version that has some extra text added to it while some exhausted monk was making a copy a hundred years after the original and a historian would call that newer manuscript an interpolation.

There's been content added that wasn't in the original. But, okay, we're not changing ancient manuscripts here. What we're doing when we interpolate is introducing new content. Usually changeable, unpredictable, dynamic. I might even say variable, values, into something else. Some piece of content that already exists like an error message you need to customize, or a generated email, or a message to congratulate you on the high score you just beat, or a simple sentence to write to the system log. In Swift, it all comes down to this.

A backslash and a pair of parentheses. That's it. As long as you can remember backslash, pair of parentheses, you know how to do string interpolation in Swift. Here's how. So step one of doing string interpolation is that I have in mind some piece of text, some string literal, a message that I want to output. Like this, the high for a particular city on a particular day is some kind of temperature. When this message is output, I want to replace city, day, and temp with the values of some example variables or constants.

Let me just go ahead and add those. In step two is I then just pick each part of this string that I want to replace like city and I'll drop in a set of that backslash, pair of parentheses that I mentioned for each one. Then inside each of those parentheses, I put the name of the relevant variable or constant that I want to use to replace it. That's it! This is string interpolation. Now from writing this in a playground that will immediately see the results of this on the right hand side with this part of the string replaced by the current values of the variables or constants.

Though typically, I wouldn't just write a string literal like this by itself. Although this does work in a playground, I would usually put this inside a println statement. I'll just copy that and paste it inside. It works the same way in a playground. But this way, it would also work in a regular program where you would see the results output to the console. But it gets better because we're not limited to just showing a single value of a variable or constant inside each of these backslash and pair of parentheses.

We can also go ahead and write an expression. I'll just to drag this back so we can see it more obviously here. I got a couple of variables, quantity, and unit price. Then inside the backslash, pair of parentheses, I just directly write quantity multiplied by unit price. That expression will be evaluated. I don't need to create some temporary variable to do it. So this is string interpolation. It's a very simple, very readable format, all down to the backslash and pair of parentheses. But this is the first time we've written an expression that uses two different variables.

It introduces an important point about what happens with expressions if they have different date and times. So let's cover that next.

 

 


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


<== предыдущая страница | следующая страница ==>
Creating constants Создание константы| Printing values and working with string interpolation

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