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

Converting values

What you should know Что вы должны знать | The structure of Swift | 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 |


Читайте также:
  1. Converting to True Components
  2. Converting values Преобразование значения
  3. Printing values and working with string interpolation
  4. Printing values and working with string interpolation

 

- Swift is a language that insists on clarity. It doesn't allow you to be vague and unspecific. We've already seen that it does type checking. We can't treat a string variable like it's an integer or the other way around and we'll see more and more of this as we go forward. This clarity is required in expressions, whether they're simple expressions in a println statement like I have here, or when we're creating another variable or in a function, Swift wants to be very specific about how to do this. Now here's what I mean, if we want to multiply together two integer variables, and these are integer variables because their initial value had nothing after the decimal point, well then this would be fine.

We multiply two Ints and we would get another integer, but if I had given one of these variables an initial floating-point value, I'll change unitPrice here, well unitPrice would now be inferred as a Double, not an Int because a Double is the default floating-point type in Swift. So in this expression we are now multiplying an integer value by a Double, by a floating-point value and Swift is going to immediately sound the alarm. We've got an error popping up over here because it isn't sure what type we want the result to be.

Do we want treat the Double as an integer and truncate it and lose what's after the decimal point or do we want to treat the integer as a Double and theoretically lose precision? Now this error is not the most straightforward. Could not find member "convertFromStringInterpolationSegment", but really the issue here is that we are trying to multiply together an integer by a Double and we're not being specific about how this should be done. And this is not just for println statements. This would work the same way if I wanted to just create a new variable based on multiplying the two of these together.

We're still going to have this issue. Quantity times unitPrice is now an integer times a Double. It's not sure how to do this. It's not sure what this result should be. Several programming languages would implicitly convert the integer here, this Quantity, and treat it as a floating-point value with the result being another floating-point value, but here's the thing that I would write in big flashing letters if I could. Swift does not and will not implicitly convert one value to another type of value. Now it is easy to convert one type of value to another.

There are simple functions to be able to do this. We've got functions like Double() that we just call, or Int() or String(), but it has to be explicit. Swift can do it easily, but it won't do it automatically, you must make it happen. This is another safety feature of Swift. If there is any potential for mismatch, for loss of information, for vagueness, then you must choose, you must be specific. So in this case when multiplying these together do I want to treat the integer as if it's a Double or the Double as if it's an integer? Well in this case I don't want to lose what's after the decimal point, so let's treat them both as Doubles.

Now it is true I could just put a.0 up here after Quantity and have that automatically inferred as a Double. You see this now works, we get rid of the error, but this is cheating. Quantity probably should be an integer. We're not going to sell.5 or.1 of a unit, so I'm going to leave that back as an Int and in the expression here what I'm going to do is wrap Quantity in a call to Double(). Now we're explicitly converting it and we have no more error.

We get our result as another Double and I could do the same thing inside the string interpolation. The expression is evaluated and we get the result here that we want. So conversion is easy to do in Swift. It just doesn't happen automatically if there is any potential for error. Now it is true that there are some conversions that throw even more potential for error. If you're trying say to convert a string value to a numeric value and the string doesn't actually hold a numeric value, well what happens? But that discussion can come later, first let's get into managing the flow of our code.

 

 


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


<== предыдущая страница | следующая страница ==>
Printing values and working with string interpolation| Converting values Преобразование значения

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