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

Declaring variables

Course details | Course details | Welcome | Welcome добро пожаловать | What you should know | What you should know Что вы должны знать | The structure of Swift | The structure of Swift Структура Swift | Writing Swift in playgrounds | Creating constants |


Читайте также:
  1. Creating optional variables
  2. Creating optional variables Создание дополнительных переменных
  3. Declaring variables Объявление переменных
  4. Linear multiple variables regression
  5. List of variables, arrays and fields

 

- The first thing we're likely to do in any programming language is make a variable. So let's start there. In Xcode, I'll make a new playground. I'll call this Variables and save it on my desktop. There's an example in the default code that, in Swift, we use the keyword var to declare a variable. It's the word var, all lower case, and then our variable name. The suggested naming convention, as in many languages, is that variable names are camel case, using a lower-case first letter. But I am not finished. I'm going to give this variable an initial value.

So I'll set it equal to 100. Many programmers at this point start wondering, "So is this an integer variable? "Specifically, can we change this to hold "a floating point value? "Could it then hold a string or a Boolean or an object? "Does any of this matter?" All good questions. We will deal with them momentarily. First, a quick but necessary sidebar. You see, var is a keyword that we have in other languages. It's in JavaScript. Var is in PHP, it's in Csharp, it's in Go. And because of that, var has a little bit of baggage that some programmers might be bringing to the table because, in other languages, this keyword var can be one of multiple options for creating a variable.

Sometimes you use var and sometimes you don't. So let me be clear here: when we make a variable in Swift, we use the keyword var to do it. It is not one of the options for declaring a variable, it is the only way we declare a variable. Every variable in Swift is declared with the keyword var. (with rising volume) Let me say that again. Every variable in Swift is declared with the keyword var. End sidebar. So we move on, and I'll declare two more variables, also giving them initial values.

As you can see from this, string values are surrounded by double quotes, and those of you coming from Objective-C will be glad to see that we no longer need the leading @ sign in front of a string. We also have Boolean, which can be true or false. Again, for those of you coming from Objective-C, that's true or false, as opposed to yes or no. Now, if the first Swift you ever saw was just these few lines of code, all using the word var, but with different types of values, you would be forgiven for thinking that, perhaps, Swift is an un-typed, or at least a loosely-typed language, that it doesn't seem to matter what kind of value a variable holds.

Maybe it's a string; maybe it's an integer; maybe it's a Boolean. Well, I would forgive you for initially thinking that, but you would be barking up the wrong tree because Swift is a type-save language. It is strongly typed. All variables in Swift are of a specific data type. The variables are integers or they are string variables or Boolean variables or arrays or some custom object, but they are something specific. They are something in particular. So what's happening here is that, when you write simple code like this, Swift will do what's called type inference.

It infers the type of the variable from the code that we've written. The compiler looks at this code and says, "Well, this is quite obviously an integer variable, "and this one is quite obviously a string variable, and this one is quite obviously a Boolean variable." We don't have to tell Swift this explicitly because it's completely obvious from these initial values that we've provided. So all variables in Swift are of a specific type. And unlike, say, JavaScript, you cannot change the type of a variable after it's been defined.

So if I've declared some variables and Swift has inferred their type, that firstName is a string, and then, later, I add another line of code like this, I would expect to see an error because I'm now trying to treat firstName as an integer. And we've got this exclamation mark appearing on the left-hand side, and also, all the text is showing up in gray in our results pane, which is a hint that Swift cannot evaluate this playground properly. If I click that, we see the error message. It's not the friendliest one in the world: "Type 'String' does not conform to protocol "'IntegerLiteralConvertible'," basically saying, you can't take firstName, which is a string, and treat it like it's an integer.

It is not going to implicitly convert an integer value into a string value. It won't do that. Now, there are all sorts of options for explicitly converting values from one type to another, but it won't just happen automatically. That's a safety feature of Swift. It's not going to implicitly change one thing into another kind of thing. "But," you might be wondering, "what if I don't, or can't, "provide an initial value for Swift to infer? "What if I want to declare a variable and then, later, "set its value?" Well, that's fine, you can do that.

What happens is, if you write a line of code like this, var myVariable, and there's no initial value, then Swift cannot infer a type because there is nothing to infer. That's okay, but it means that this code, by itself, is not enough. And if I try and leave this alone, I'll see that I've got the exclamation mark showing up over here. It would also give me a compile error if I was writing this in a proper project in Xcode. And the error would be that "Type annotation is missing." Swift is saying, "I don't know what this variable "is supposed to be," because, when we declare variables in Swift, either we provide an initial value so that Swift can easily infer the type, or, if we don't do that, then we must say explicitly what the type of this variable is.

And we do this by writing a colon after the variable name and then the data type we want for that variable. So I'm going to ahead and make this an Int. This is now showing up. There's no exclamation mark on the left and all the text is showing up in black. So it seems that Swift understands this code just fine. So this is called the type annotation, the colon and then the data type. Think of the colon as meaning 'is of type,' so myVariable is of type Int, and Int being the classic Swift integer data type.

Now, this point is where some tutorials would go through a big list of all possible data types and their sizes and ranges. I'm not going to do that here. We'll talk about some of these in more detail later. But I'll leave some of the specifics as an exercise for you. For now, know that straightforward data types include Int, for integer, Float and Double, for 32 and 64-bit floating point types. We have a very powerful string type. There's also a single-character type, and there's the Bool with, again, true or false.

And notice that all the types here, which are showing up in purple -- they're color-coded in Xcode -- they begin with an uppercase first letter, even the simple ones like Int. Now, there are, of course, more complex data types we can use. There are collections, like arrays and dictionaries, or custom objects. We will see these all later. Now, if you want to be explicit about the data type, and also provide an initial value, I could certainly go ahead and do that. Say you're creating a variable called lastName, saying it's a string and giving it a value, or saying it's a Boolean or an integer and giving those specific values, as well.

I'm getting a complaint here about this variable, just because it already exists here. Cannot put the (mumbling). I've declared it twice. That's not going to work very well. We'll change that and then let it go ahead and update. This is perfectly acceptable code. So, var lastName, the type annotation, and then the initial value. But if a value is so obviously a string or so obviously a Boolean or so obviously an integer, there is simply no need for the type annotation. These are optional pieces.

You can remove them if you want to. So let me clear up a misconception. The point of type inference in Swift is not to try and obscure or hide the data types from us as programmers. It's quite the opposite. It assumes that, when we write code like this, we deeply understand what our data types are. Type inference is simply there to make code more concise and more readable. So if the data type is blindingly obvious, both to us and to the compiler, then we just let Swift infer it. But if it's not obvious, particularly when we're not providing a default value, as with this interestRate variable down here, then we need to provide that type annotation.

 

We need to say what the type is. And you will see this kind of thing a lot, that many decisions in the Swift language are to improve the clarity and the readability, but also the safety, of our code.

 


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


<== предыдущая страница | следующая страница ==>
Writing Swift in playgrounds Написание Свифт на игровых площадках| Declaring variables Объявление переменных

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