Mastering macOS Programming
上QQ阅读APP看书,第一时间看更新

Integers

Most of the time, you will use Int for all integers. Apple's advice is to use Int for all cases except where you need to work with a specific size of integer. Similarly, Int should be preferred to UInt even for values that cannot be negative, unless you need an unsigned integer type of the same size as the platform's native word size.

If you're not sure what that means, don't worry about it; just use Int.

The following table shows all the integer types available in Swift, along with their maximum and minimum values (unsigned minima are, of course, 0):

You have a number of options when using Int. Very handy is a feature that lets you add underscores in any way that helps you to present the number more clearly (from a human perspective), which the compiler simply ignores:

let million = 1_000_000

Can anyone here claim they have never been out by a factor of ten due to a 0 typo?

Integers can also be expressed in binary, octal, and hexadecimal form:

let myBinary = 0b101010
let myOctal = 0o52
let myHexadecimal = 0x2a

All three of the numbers are of the type Int with a value of 42. Thus, they can be used together in calculations:

let c = myBinary + myOctal 

No complaints from the compiler here.

To declare a non-whole number, you have two native options. You can declare a decimal number with the Double type:

let myDouble = 42.0 

In this case, Swift will infer myDouble to be of type Double (whatever you care to name it, it's not understanding myDouble).

So, if you need a Float, you'll need to make the type explicit, as follows:

let myFloat: Float = 42.0 

Number types are not automatically cast to compatible types as they are in many languages, so conversion from one number type to another needs to be done explicitly. The following code will produce a type error:

let myResult: myFloat * myDouble 

But each number type has an initialization method that will take a value of another number type as its argument:

let a = Double(42) 
let b = Int(4.9)
let c = Int("42")

Note that the value of b will be 4, as one would expect of conversion from a decimal type to an integer type. To round a double to the nearest integer, you'll need to use round:

let d = round(4.9) 
let e = Int(d)

The following line is a little more succinct:

let e = Int(round(4.9))