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

Defining and using enumerations. - Sometimes it's useful to restrict our own options

Creating loops in Swift Создание петель в Swift | Defining functions | Defining functions Определение функции | Creating and using arrays | Creating and using arrays Создание и использование массивов | Using dictionaries | Using dictionaries Использование словарей | Understanding tuples | Understanding tuples Понимание кортежи | Creating optional variables |


Читайте также:
  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. C) Interview your partner using the questions in
  4. Choose a verb from the list and complete the text using Past Continuous or the Past Simple.
  5. Complete the following sentences using an appropriate form of the verb.
  6. Creating and using arrays
  7. Creating and using arrays Создание и использование массивов

 

- Sometimes it's useful to restrict our own options. Let's say I'm planning to build an airline booking application, and I want a variable called travelerSeatPreference, to say whether someone prefers window, middle, or an aisle seat. Now, if I define this as an Int, this will have a range of... well, it's big. Compiled in a normal 64-bit machine, an Int has a range of two to the power of 64 minus one, which we might as well say is a range of several bazillion, kajillion possible values. But I want it to represent only window, middle, or aisle.

Now, sure, in my program, I could just give it a value of, say, two, and just keep it in my head that, in my application, zero should mean aisle and one should mean middle and two means window. But there's nothing that actually stops this variable from being changed to five or 73 or 385 million. Okay, it is true there are a few specialized integer types. After all, when I'm defining the type annotation up here and I type in Int, I will see not only Int but Int16, Int32, Int64, and even Int8 -- eight bits for smaller and smaller integers.

But even the smallest, the Int8, has 256 possible values. Now, it is true I could also store this as a string if I wanted to do that. And then I could just go ahead and give this a string value of window, but again, there's nothing really that would stop that from being set to all sorts of different values, and someone could change that to a traveler seat preference of 'banana,' and that would compile just fine. So we want to wait to define some data that has a more specific range of possible values.

And we have that with enumerations, or enums. Now, enumerations, of course, exist in many languages, but once again, in Swift, we do things similar to, but not exactly the same as, in other languages. To do this, what we'll do fist is, define the enum, define the possible values. If we want to have a variable that represents a seat preference, well, what possible values could that be? To set this up, we use the word enum, then the name of our new enumeration, and then a code block, the opening and closing curly brace.

Now, the style guideline here, because we are defining a new data type, not a new variable yet, is that we use an uppercase first letter for our new enumeration. In this case, I'm saying SeatPreference will be the new type. I want to be able to create variables or constants of the type SeatPreference, just as I can create variables or constants of type Int or type string. So inside these braces, I list the possible values that I want allowed. And you can use your own words here, whatever is meaningful to us.

In Swift, these are written as cases, similar to a switch daemon, so we are using the case keyword, although, in an enumeration, we don't need a colon. It's just case Window, case Middle, case Aisle, case NoPreference. So I'm adding this fourth option here, in case someone hasn't expressed a preference. I can write these as individual cases or, another alternative is, you actually can write them just on one line, just separated by commas: case Window, comma, Middle, comma, Aisle, comma, NoPreference. Personally, I find separate lines are more readable.

So each of these cases is referred to as a member, or a member value, of the enumeration. There's no limit to the amount of these. If I wanted 100 different member values in my enumeration, that's fine. It's my decision what's here, and the words are up to me. Again, these words are typically written with an uppercase first letter. This is not enforced, it is just accepted practice. Now, this is just preparation. What this all means after we're done is, we can use this new enumeration, SeatPreference, as a data type.

So I can create a new variable. I'll call it var jenPrefers. Start to type. We can get autocomplete here. SeatPreference, using the type annotation. So, a new variable called jenPrefers, of type SeatPreference. It now has a type, although it doesn't have a value. So I can add a value to this. jenPrefers equal to SeatPreference, dot, and it'll automatically show us that code complete dot Aisle, or Middle, or NoPreference, or Window. Let's just go ahead with Aisle.

This is a strongly-typed variable of type SeatPreference, and it has the value Aisle. Although, because this variable, jenPrefers, is already typed as a SeatPreference enumeration, I can, in Swift, use a shorthand format. I don't need to say SeatPreference. That's a little bit redundant. I can just say, dot Aisle or dot Middle or dot Window because Swift knows that the only possible values for this variable are SeatPreference member values. So I can just use this shorthand format.

But having said that, just like with other variables or constants, if I already know what value I want to set for a new variable or constant, I can just use type inference and do it all on one line, not two. So, create a new variable, royPrefers equals SeatPreference dot Window. And by providing a specific SeatPreference option, this will now be type-inferred as a SeatPreference with that specific value. The benefit of doing all this is not just that these are restricted to specific values, but also that, later on, in the code, I could do something like this.

We'll add a new switch statement on that new variable, and inside that, just do some cases. Now, these are cases within the switch statement, of course. Case dot Window, case dot Aisle, case dot Middle or case dot NoPreference. And the great thing is that the swift compiler will understand all the possible cases that this variable is allowed to be. Again, with a switch statement in Swift, I have to be exhaustive. But the compiler recognizes that I am being completely exhaustive here.

There are four possible options, and I'm checking them all so I don't even need a default case in this switch statement. Again, because the only options are SeatPreference options, this is strongly-typed as a SeatPreference variable. I can just say, case dot Window, case dot Aisle, case dot Middle, and so on. Now, here's the thing: even if you don't immediately want to write your own enumerations, you cannot avoid these. You will find that they're common in the Apple frameworks as a way to represent choices. And when you read through other people's Swift code or examples from Apple, you're likely to see many variables being set to a dot something value, or checked for a dot something value.

And that's the clue that this variable must be typed as some kind of enumeration. In Xcode, you can option-click a variable name to see what kind of enumeration it's defined at, but you will see this a lot. Enumerations in Swift are more powerful than in most languages, and they do go further than this. You can extend enumeration definitions to store internal values, you can even add properties and methods to add functionality, although, most of the time, what we've covered here is going to be all you need.

 

 


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


<== предыдущая страница | следующая страница ==>
Creating optional variables Создание дополнительных переменных| Defining and using enumerations

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