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

Using the switch statement

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 | Converting values Преобразование значения | Writing if statements |


Читайте также:
  1. A form of cryptosystem in which encryption and decryption are performed using the same key. Also known as conventional encryption.
  2. Answer the following questions using your own words but taking into account the
  3. B) Read the text again and mark the statements True (T), False (F), Not Stated (NS).
  4. C) Interview your partner using the questions in
  5. CASH FLOWS STATEMENTS
  6. Choose a verb from the list and complete the text using Past Continuous or the Past Simple.
  7. Complete set of automation of management a switch 110 kV with the functions DBRS, ARI, FLD (fixing of line disconnecting)

 

- When you realize you're writing code that repeatedly checks one variable from multiple different values, perhaps something like this, then a switch statement is a better idea than having multiple if statements, just one after the other. Now just as with if statements, if you've worked in any other language that has the switch keyword, then writing a basic switch statement in Swift isn't drastically different, and you would probably find this code fairly readable and understandable. But just as with the if statements, there are important things to know, things that are true about switch statements in Swift that are not true in other languages.

Alright, so basic syntax, if this is new to you or if you need a refresher. Whenever you see a switch statement, you know you're evaluating a single item, whether that's a variable or a constant, and you're reacting to multiple possible values of that. So let's imagine we've got an integer called windSpeed that could be something in the range zero through twelve. So to check this using a switch statement, it begins simply. Just the keyword switch and the name of the piece of data that we want to check, some variable, some constant. And then a set of opening and closing curly braces.

But when we write a switch statement, we don't have just one important keyword, but two. Switch and case because inside this code block for each switch we will have multiple case keywords. That's how we say what different values we want to check for and react to. Each case ends with a colon, not a semi-colon. And this colon is not optional like the semi-colons are at the end of a statement, so watch out for that. So we'll have multiple cases. So we're switching on the windSpeed variable. We say in the case that it's zero, do one thing.

In the case that it's one, do something else. In case it's two, do yet another thing, etc., etc. Now after each case and after the colon, we then have one or more lines of code that will execute if that case is true. And in Swift, as soon as we hit the first case that is true, we will execute that case and then we're done with the switch statement. We would drop out to the end, past the final closing curly brace of the switch, and continue on. Nothing particularly unusual about any of this if you've worked with switch statements in other languages.

Having said that, if I wrote code like this in a playground, this would not compile in Swift yet. Here's why. First, a switch statement in Swift must be exhaustive. What this means is if you're testing, say an integer constant, as we are here, you can't just have a handful of cases for a few specific values and just ignore all the other possible values that this integer could possibly be. You need to make sure that all possible values are handled in the switch. In my case, I may know that my logic means I'm only ever going to have values from zero through twelve, so I'd provide those cases, but this is, after all, an integer, and I've got several billion more values this could be.

Now the simplest way of dealing with this inside a switch is to have a default case. We just use the keyword default with a colon. We don't actually need the case keyword here, and this allows us to have a catch-all situation. Default simply means all the other cases weren't true, so do this. Now in some languages, like objective C and regular C, you will often see code with several empty cases written in them, one right after the other. This uses the concept of fall through that exists in some languages.

We would fall through from one case into the next, effectively sharing code across multiple cases. And in languages that do have this fall through behavior, you often need an explicit break statement at the end of the code for each case so that you don't just go and fall through into the next case, so in case 3 and case 4 they end with a break statement here. But fall through is another thing that can cause hard-to-find bugs, So in Swift, by default, there is no automatic, no implicit fall through from one case to another.

And that means each case must have it's own code, its own functionality. Empty cases like what I'm writing here, wouldn't compile in Swift. It would complain about them. We need to have at least one statement to execute in each of these cases. And in Swift, as soon as we hit a case that's true, we'll execute the statements in that case, and then we're done. We jump to the end of the switch statement and continue on. Now if you do have a situation where you wanted to explicitly do nothing in a particular case, you can write a break statement in Swift.

So, for example here, if I wanted to have the default case didn't do anything, I'd put that in and I'd put break. But these are only needed when you need to explicity end a case, either by itself, or if you had some logic, some branching, going on inside that case. So while we can't write empty cases one after another, we can test for multiple values, and one of the best ways of doing it in Swift is that we can provide ranges of values to check for. Now this is something that isn't possible in the switch syntax of many other languages.

So if I want to test this integer to see if it's somewhere between zero and three, I would write this. case 0...3. These three dots is what's called a range operator in Swift. This is a very concise way of saying, create a range with the values on both sides of the... and all the values in between. So here any value from zero through three, or from four through six, or seven through nine, or ten through twelve, will count as true for this case.

Now this is known as the closed range operator. There are two range operators in Swift. This is one of them, we'll see the other one in a moment because they're not just important for switch statements. They're also extremely useful when creating loops. Now there are some advanced features of switch statements in Swift that can take this even further, like using where clauses and creating temporary variables, but we'll see these a little later on. This is enough to keep us moving forward. So these are the important things to understand, particularly when coming from another language with switch statements.

That they must be exhaustive in Swift, and all values handled somewhere in the code. That we can provide ranges of values to check on, and that each case must contain at least one statement. There is no automatic or implicit fall through in Swift from one case to the next. And as soon as we hit a case that's true, we'll execute just the code in that case, and then we're done. We jump out of the switch statement and move on. So let us move on and create some loops.

 

 


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


<== предыдущая страница | следующая страница ==>
Writing if statements Написание если заявления| Using the switch statement Использование Переключатель

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