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

Creating optional variables

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


Читайте также:
  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
  7. Creating constants

 

- Tuples aren't the only new thing in Swift. Another concept not found in many languages, including C and Objective-C, is that of optionals. Optionals let us describe a situation where sometimes we have a value and sometimes we don't. All right, let me unpack that statement, because there are some subtleties to this. If I declare a standard variable in Swift, without initializing it, without giving this a value, that's fine; I can do that. So here I'm saying I want an integer variable called temperature.

But this must be given a value before we use it. Swift does not default an integer variable to zero or default a string to an empty string, the way that some other languages do. And Swift will enforce the fact that a normal variable must be initialized before we attempt to use it. If I try to do any kind of operation on this, adding to it, printing it, I'm going to get an error telling me that this is not initialized and this is simply not allowed. So we've got this popping up over on the side, variable 'temperature' is used before being initialized.

We can't do this in Swift. All right, you might think, let's just go ahead and give this a basic initial value. I could just go ahead up here and give that an initial value of zero. I wouldn't even need the type annotation at that point. And that would make the error go away. But this is a bad idea for us in this case, and here is why: let's imagine that the value of this temperature variable is intended to be obtained by calling some function. It doesn't really matter what that function is, but let's say it's something that went out to the Internet and retrieved the current temperature and updated this variable.

But the problem is, sometimes we don't have a connection, so we can't get a value. We weren't able to get to the current temperature. We weren't able to update this variable. Well, in this case, I don't want this temperature variable to have a value of zero because zero is a valid temperature. It means it's wintertime and it's freezing. And there's a very big difference between saying, "Today's temperature is zero," versus saying, "We weren't able to obtain today's temperature." Data that's zero and data that's missing are two very different ideas.

So I'm going to go up here and remove that initial setting to zero, so that's bringing the error back here. So the situation that we have, we want to use optionals. Optionals allow us to say that, for any particular variable, we may have a value, and if we do, it will be of a particular type. It'll be an integer or a string or a Boolean. But we may have no value at all -- not zero, not empty string, not false... nothing, or nil, the absence of a value. As we've seen, by default, variables are not allowed to have nil values; they're not allowed to be devoid of a value before they're being used.

By default, they must be initialized. So you have to choose to opt into these optionals, to support this on a variable-by-variable basis. So with this example, to support this idea that temperature might be nil, I would mark this temperature variable not as just an Int, but an optional Int. And I do that by adding a question mark immediately after the type, not even a space between them. So Int? here. And notice that the error has immediately gone away. Swift understands that this variable may be either an integer or it may be nil, nothing else.

Being optional doesn't mean it might be a string or might be a floater or might be a double. It's either going to be a valid Int or it's nil. And nil, as you can see, is what it's going to be considered first, because there's been no value assigned. And we're no longer getting an error. This is actually writing out the message, "The temperature is nil degrees." Well, this message isn't great. The thing is, if we're going to do this, we often don't need just the variable to support being an optional and having a nil value, we need to be able to test for that, as well.

So I had this message, but let's say that, before I write this message out, I need to test whether this does or does not have a value. So I can just ask, if temperature is not equal to nil, then we will do the print line and we should have some kind of temperature, and then close that... (keyboard clicking) and we're fine. We have no error anymore. Having said that, right now we would never hit this line because the playground can tell that the value of temperature is nil. So let me fake this actually having a value, just to test that.

Temperature equals 65. Now we should count that temperature is not equal to nil, we should hit this printLine statement. And we do. What we get here is, "The temperature is Optional(65) degrees." I'm getting this extra text here. Because the temperature variable had its type changed from integer to optional integer, if I just have this basic code spitting out whatever the value of temperature is, it'll be wrapped up in that optional text, because it isn't a plain Int, it's an optional Int.

So if I don't want that extra optional text, what I need to do is, extract the value out of it. I need to add something to say that I know this is an optional variable, but I am positive it has a value and I just want that value. And to do that, I add an exclamation mark right after the use of the variable name, so not just temperature, but temperature!. This, again, is inside our backslash pair of parentheses, so it's using string interpolation to pull this value out.

What we're doing here is actually called forced unwrapping. We are forcing that optional variable, saying we know it has a value and pulling that value out. But we only ever do this if we are positive, if we are sure, that this optional actually does have a value. If you use the exclamation mark to forcibly unwrap an optional variable that is actually nil, you will get a run-time error. But, of course, we tested for this not being nil, so we're good. But it's not just your own code that you'll need optionals for.

We use optionals in many places in Swift. Here's one example: We've seen this dictionary example a couple of times. Multiple key/value pairs. Now, later on in my code, what I want to be able to do is, pull some value out of that dictionary. Var result equals, and I'm using NV as a way to try and pull information out. The thing is, this result variable, this new variable that I'm creating, will be automatically typed as a optional because this key may or may not exist in the dictionary.

So if it doesn't exist, we would want any result to be nil, and that's actually what we're getting because NV does not exist in the dictionary as a key. The playground can tell there is no NV key in the dictionary. Again, what we can do when dealing with optional values is, deal with them in two steps. We first try and retrieve a value, and then we will try and test to see if it is, or if it is not, equal to nil. We will deal with it. However, there's another option. We can kind of combine these two things into one step, so only dealing with values if they exist.

It's called optional binding. Now, this might look a little strange the first time you see it. Let me just comment out that old optional. We're still working with the dictionary here. Going to add a little code here. And this is the strange-looking part. We're using 'if let.' Well, really, what we're doing here is trying to say, we create a constant here. Let result equals states, and using NV to get to that key. But embedding that inside an if statement is going to try and do this thing called optional binding.

So we attempt to retrieve a value from the dictionary and put it in a constant called result. And the name is not important here. This is up to us. So if the key matches, then this constant will have a value. This if statement will be treated as true and we will drop in and print that state result out. But, on the other hand, if nothing was found for this key, we're just going to say, no, we don't have any match; in fact, this result variable, or rather, result constant, will not exist.

 

We will have nothing that we could write out even if we wanted to. Right now, because the playground understands the code that I've written, we are getting the "No matching key found," because it knows that NV doesn't exist. But if I change that to using a key that actually does exist, we should see the printLine statement will actually write out, "The state name is California." Now, one benefit of doing this optional binding option here, using if let, is that we do not need to forcibly unwrap the result that we get back. We don't need to use that exclamation mark after it, because it's already understood that there must be a value in this result constant because this counted as true.

 

Otherwise, it wouldn't even exist. So this is optionals. It's all about these question marks and exclamation marks that follow the variable. And we will see more of them as we go forward. One last thing to point out here: if you are an Objective-C user, know that optionals in Swift are not the same thing as nil pointers in Objective-C. In Swift, they are much more widespread, much more common. And, while in Objective-C, nil pointers were used to represent a nonexistent object, in Swift, any kind of value can be defined as optional, not just objects.

 

So as you read more and more Swift code, you will see a lot of these exclamation marks and question marks used to describe these situations, where we may or may not have a value, and after we understand that we may or may not have a value, we need to be able to extract that value out of the optional variables that we have.

 

 


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


<== предыдущая страница | следующая страница ==>
Understanding tuples Понимание кортежи| Creating optional variables Создание дополнительных переменных

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