Counting with Numeric Types

Let’s play with some more math. We’ll create another variable:

 var​ bar = 0

That looks good, and since it’s a variable, we can change its value:

 bar = 0.5

Oh, no! We get another error, and this time without an instant fix. Worse yet, the description is unhelpful: “Cannot assign a value of type Double to a value of type Int.”

So what’s the deal? Can Swift seriously not convert between floating-point numbers and integers? Actually, Swift can, but our variable bar cannot. The problem is that we never specified what the type of bar is, so the Swift compiler made its best guess. Replace the second bar = 0.5 line with the following:

 bar.​dynamicType

The dynamicType property allows us to see what type a value has. In the right pane, we see that the type evaluates to Int.type. That makes sense: since the original value was 0, Swift took a guess and assumed we would want an integer, not a floating-point type. This inferring of types is called, appropriately, type inference.

We could tell Swift to use a floating-point type by using 0.0 as the initial value; try that and you’ll see the dynamicType becomes Double.type. But if we want a given type, we can and should just declare it that way. Change the declaration like this:

 var​ bar : ​Double​ = 0

Now Swift doesn’t need to infer anything: we’ve explicitly declared that we want bar to be a Double, meaning a double-precision floating-point type.

There’s also a lower-precision floating-point type, Float, and a Boolean type Bool. In some languages, such as C, you can cast between integers, floats, doubles, and Bools, and the worst that will happen is that the compiler will warn you about loss of precision. Swift forbids this altogether, even if you wouldn’t be losing anything. Try this:

 let​ myInt = 1
 let​ myDouble : ​Double​ = myInt

This pops up an error saying “Int is not convertible to Double.” To create myDouble, we need to tell Swift to create a new Double:

 let​ myInt = 1
 let​ myDouble = ​Double​(myInt)

The second line here uses Double’s initializer to create a new Double, using the value passed in as a parameter.

Swift’s numeric types work with the usual arithmetic operators popular in other languages: +, -, *, /, and %. The last one, the modulo or “remainder” operator, works not just on Int but also Float and Double, which isn’t always true of other languages. On the other hand, thanks to strong typing, Bools aren’t just numeric values, and thus none of these mathematic operators work with Boolean values. And that’s a good thing because what would “false divided by true” mean, anyway? Instead, we use the usual Boolean operators ! (NOT), && (logical AND), and || (logical OR).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.4.44