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

Writing if statements

The structure of Swift Структура Swift | Writing Swift in playgrounds | Writing Swift in playgrounds Написание Свифт на игровых площадках | Declaring variables | Declaring variables Объявление переменных | Creating constants | Creating constants Создание константы | Printing values and working with string interpolation | Printing values and working with string interpolation | Converting values |


Читайте также:
  1. B) Read the text again and mark the statements True (T), False (F), Not Stated (NS).
  2. CASH FLOWS STATEMENTS
  3. Consider the following statements and say if you agree or disagree with them. Use the introductory phrases given in the previous Units.
  4. English phonemes in writing
  5. Exercise 2 Rearrange the words bellow to make statements.
  6. Exercise 2 Rearrange the words bellow to make statements.
  7. Exercise 2. Rearrange the words bellow to make statements.

 

- There's not much point having variables if you're not going to ask questions about them and their values. So let's cover the classic if statement to manage the flow of logic through our code. Now like many other things in Swift, if statements here are clean, they're safe and they're all familiar. If you've written any JavaScript, C, C++, C Sharp, PHP, Java ActionScript, I could tell you just try writing an if statement. Write what you know. What you'd write, which would be something like this, would work in Swift. It's an if statement so back as basic as it gets but come back.

See, this doesn't mean we're done here. Because for most programmers, there are a few distinctions worth making about if statements in Swift. First, you do not need parentheses around your condition, the way that you do it in many other languages. You can have them if you find it helpful or more likely if you're just so used to writing them that is habitual. But like semicolons, they're simply not necessary in Swift. With the simple condition like this, parentheses don't add anything so removing them just makes it more readable.

The next thing you need to know about if statements in Swift is that one parentheses may be optional. Curly braces aren't required for each branch of the condition. You probably already know that in many C-Star languages, if you write a simple if statement when you want to execute a single line of code if a condition is true, then you don't have to have that single statement surrounded with curly braces. You could just write code like this. But if you've programmed through any length of time, you will also know that this so-called feature of C-Star languages, once you've mixed this in 100 of lines of other code, is easy to miss and it can cause very subtle but nasty face palm, "Oh my God, I can't believe I didn't see that logic errors." So this is not an option in Swift.

Even with an if condition that only has one line to execute. When a condition is true, this is a code block. This code block must be surrounded with curly braces. You will get a compile error if you don't have one. To me, these distinctions are a perfect example of the choices made in the Swift programming language. You don't need parentheses around a simple condition because they add no value. Removing them just makes it clear and readable. You do need braces around your code blocks because they make things safer. We can, of course, follow our if statement block with an else, unless again, we'd need braces around the code block.

You could, of course, also chain multiple if statements and you could nest one inside another but don't nest too deep. Swift can certainly handle that just fine. But multiple levels of nested ifs are difficult to read and prone to making program errors. If we do have to have more complex conditions, there are more readable ways to manage it than lots of nested if statements. Now this condition must evaluate as either true or false. Now this, of course, is not unusual. I'm stressing the words true and false so the C programmers among you understand that you can not just have a condition that test and enter your value for being either zero or nonzero.

This won't work in Swift. The condition must evaluate as a Boolean. So things like if a is greater than 50, true or false. If b is less than zero, true or false. If c is equal to zero and to check equality in Swift, like most other C-based languages, we use the double equals. Single equal sign after all is assignment. It would set a value, not to check a value. You'll get an error if you accidentally try to assign inside the condition. For checking inequality, it's the exclamation mark, equal sign here.

Nothing particularly unusual about this. Likewise, we can check for multiple conditions at the same time. We can either use the logical AND operator, the double ampersand for AND, or the double pipe for the logical OR. Now when you have multiple conditions to check, this is one of the places that you may choose to add parentheses to make the condition more specific. In this case, if balance is less than zero, AND hasCreditLine, assuming this is a Boolean here, or balance is greater than or equal to zero. If either of these worked out as true, this condition will be true.

But of course, if statements aren't the only way to manage program, folks. So let's take a look at switch statements and how they work in Swift.

 


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


<== предыдущая страница | следующая страница ==>
Converting values Преобразование значения| Writing if statements Написание если заявления

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