Chapter    3

It’s All About the Data

As you probably know, data is stored as zeros and ones in your computer’s memory. However, zeros and ones are not very useful to developers or app users, so you need to know how your program uses data and how to work with the data that is stored.

In this chapter, you look at how data is stored on computers and how you can manipulate that data. You then use playgrounds to learn more about data storage.

Numbering Systems Used in Programming

Computers work with information differently than humans do. This section covers the various ways information is stored, tallied, and manipulated by devices such as your iPhone and iPad.

Bits

A bit is defined as the basic unit of information used by computers to store and manipulate data. A bit has a value of either 0 or 1. When computers were first introduced, transistors and microprocessors didn’t exist. Data was manipulated and stored by vacuum tubes being turned on or off. If the vacuum tube was on, the value of the bit was 1, and if the vacuum tube was off, the value was 0. The amount of data a computer was able to store and manipulate was directly related to how many vacuum tubes the computer had.

The first recognized computer was called the Electronic Numerical Integrator and Computer (ENIAC). It took up more than 136 square meters and had 18,000 vacuum tubes. It was about as powerful as your handheld calculator.

Today, computers use transistors to store and manipulate data. The power of a computer processor largely depends on how many transistors are placed on its chip or central processing unit (CPU). Like the vacuum tube, transistors have an off or on state. When the transistor is off, its value is 0. When the transistor is on, its value is 1. Apple’s A8 processor, which was introduced with the iPhone 6, has a dual-core ARM processor with more than 2 billion transistors (see Figure 3-1). This was up from 200 million transistors from the A5 processor and up from 149 million transistors on the A4 processor that was in the iPhone 4 and the first iPad.

9781484214893_Fig03-01.jpg

Figure 3-1. Apple’s proprietary A8 processor (Source: Wikipedia)

Moore’s Law

The number of transistors on your iPhone’s or iPad’s processor is directly related to your device’s processing speed, graphics performance, memory capacity, and the sensors (accelerometer, gyroscope) available in the device. The more transistors there are, the more powerful your device is.

In 1965, the cofounder of Intel, Gordon E. Moore, described the trend of transistors in a processor. He observed that the number of transistors in a processor doubled every 18 months from 1958 to 1965 and would likely continue “for at least 18 months.” The observation became famously known as Moore’s law and has proven accurate for more than 55 years (see Figure 3-2).

9781484214893_Fig03-02.jpg

Figure 3-2. Moore’s law (Source: Wikipedia)

Note  There is a downside to Moore’s law, and you have probably felt it in your wallet. The problem with rapidly increasing processing capability is that it renders technology obsolete quickly. So, when your iPhone’s two-year cell phone contract is up, the new iPhones on the market will be twice as powerful as the iPhone you had when you signed up. How convenient for everyone!

Bytes

A byte is another unit used to describe information storage on computers. A byte is composed of 8 bits and is a convenient power of 2. Whereas a bit can represent up to two different values, a byte can represent up to 28, or 256, different values. A byte can contain values from 0 to 255.

Note  In Chapter 13, we discuss Base-2, Base-10, and Base-16 number systems in more detail. However, we will introduce these systems in this chapter so you can understand data types.

The binary number system represents the numerical symbols 0 and 1. To illustrate how the number 71 would be represented in binary, you can use a simple table of 8 bits (1 byte), with each bit represented as a power of 2. To convert the byte value 01000111 to decimal, simply add up the on bits, as shown in Table 3-1.

Table 3-1. The Number 71 Represented as a Byte (64 + 4 + 2 + 1)

Table3-1.jpg

To represent the number 22 in binary, turn on the bits that add up to 22, or 00010110, as shown in Table 3-2.

Table 3-2. The Number 22 Represented as a Byte (16 + 4 + 2)

Table3-2.jpg

To represent the number 255 in binary, turn on the bits that add up to 255, or 11111111, as shown in Table 3-3.

Table 3-3. The Number 255 Represented as a Byte (128 + 64 + 32 + 16 + 8 + 4 + 2 + 1)

Table3-3.jpg

To represent the number 0 in binary, turn on the bits that add up to 0, or 00000000, as shown in Table 3-4.

Table 3-4. The Number 0 Represented as a Byte

Table3-4.jpg

Hexadecimal

Often, it will be necessary to represent characters in another format that is recognized by computers, namely, the hexadecimal format. You will encounter hexadecimal numbers when you are debugging your apps. The hexadecimal system is a base-16 number system. It uses 16 distinct symbols: 0 to 9 to represent the values 0 to 9 and A to F to represent the values 10 to 15. For example, the hexadecimal number 2AF3 is equal in decimal to (2 × 163) + (10 × 162) + (15 × 161) + (3 × 160), or 10,995. Figure 3-3 shows the ASCII table of characters. Because 1 byte can represent 256 characters, this works well for Western characters. For example, hexadecimal 20 represents a space. Hexadecimal 7D represents a right curly brace (}).

9781484214893_Fig03-03.jpg

Figure 3-3. ASCII characters

Unicode

Representing characters with a byte worked well for computers until about the 1990s, when the personal computer became widely adopted in non-Western countries where languages have more than 256 characters. Instead of a 1-byte character set, Unicode can have up to a 4-byte character set.

To facilitate faster adoption, the first 256 code points are identical to the ASCII character table. Unicode can have different character encodings. The most common encoding used for Western text is called UTF-8. As an iPhone developer, you will probably use this character encoding the most.

Data Types

Now that we’ve discussed how computers manipulate data, we will cover an important concept called data types. Humans can generally just look at data and the context in which it is being used to determine what type of data it is and how it will be used. Computers need to be told how to do this. So, the programmer needs to tell the computer the type of data it is being given. Here’s an example: 2 + 2 = 4.

The computer needs to know you want to add two numbers together. In this example, they are integers. You might first believe that adding these numbers is obvious to even the most casual observer, let alone a sophisticated computer. However, it is common for users of iOS apps to store data as a series of characters, not a calculation. For example, a text message might read “Everyone knows that 2 + 2 = 4.”

In this case, the example is a series of characters called a string. A data type is simply the declaration to your program that defines the data you want to store. A variable is used to store your data and is declared with an associated data type. All data is stored in a variable, and the variable has to have a variable type. For example, in Swift, the following are variable declarations with their associated data types:

var x: Int = 10
var y: Int = 2
var z: Int = 0
var submarineName: Int  = "USS Nevada SSBN-733"

Data types cannot be mixed with one another. You cannot do the following:

z = x + submarineName

Mixing data types will cause either compiler warnings or compiler errors, and your app will not run.

Table 3-5 gives examples of the basic data types in Swift.

Table 3-5. Swift Data Types

Type

Examples

Int

1, 5, 10, 100

Float or Double

1.0, 2.222, 3.14159

Bool

true, false

String

"Star Wars", "Star Trek"

ClassName

UIView, UILabel, and so on

Declaring Constants and Variables

Swift constants and variables must be declared before they are used. You declare constants with the let keyword and variables with the var keyword. Constants never change during the program, but variables do change during the program.

There are two ways to declare variables: explicit and implicit.

Here is the syntax for explicit variables:

var name: type = value
var firstNumber: Int = 5

However, declaring the type is normally optional, and removing the type shortens the code and makes it easier, because there is less code to type and maintain.

Here is the syntax for implicit variables:

var name = value
var firstNumber = 5

You can use implicit most of the time because Swift is smart enough to figure out what the variable is by what you assign to it.

If a variable isn’t going to change, then you should declare it as a constant. Constants never change. Constants start with the keyword let, as shown here:

let secondNumber  = 10

To best understand how variables and constants are declared, here are two examples:

let maximumNumberOfStudents = 30
var currentNumberOfStudents = 5

This code can be read as follows: “Declare a new constant called maximumNumberOfStudents, and give it a value of 30. Then, declare a new variable called currentNumberOfStudents, and give it an initial value of 5.”

In this example, the maximum number of students is declared as a constant because the maximum value never changes. The current number of students is declared as a variable because this value must be incremented or decremented after the student enrollment changes.

Most data you will use in your programs can be classified into four different kinds—Booleans, numbers, strings, and objects. We will discuss how to work with numbers and object data types in the remainder of this chapter. In Chapter 4, we will talk more about Boolean data types when you learn how to write apps with decision making.

Note  Localizing your app is the process of writing your app so users can buy and use it in their native language. This process is too advanced for this book, but it is a simple one to complete when you plan from the beginning. Localizing your app greatly expands the total number of potential customers and revenue for your app without your having to rewrite it for each language. Be sure to localize your app. It is not hard to do and can easily double or triple the number of people who buy it. For more information on localizing your app, visit Apple’s “Build Apps for the World” site: https://developer.apple.com/internationalization/.

Optionals

Swift introduces an important concept called optionals that developers need to understand. Even for experienced iOS developers, this concept is new. Optionals are not a hard topic to understand, but they take some time to get used to.

Use optionals when a value may be absent. An optional says the following:

  • There is a value assigned to a variable or there is no value.

There are times when a constant or variable might not have a value. Listing 3-1 shows an example of the integer initializer called Int(), which converts a String value to an Int.

The constant someInteger is assigned the integer value 42. someInteger is also assigned the type of Int?. The question mark indicates that it is an optional type, meaning that the variable or constant’s value may be absent. See Listing 3-2.

Line 2 in Listing 3-2 has a problem. It is not possible to convert “Hello World” from a String to an Int. So, the value of someInteger is said to be absent or nil, because on line 2, someInteger is inferred to be an optional Int.

Note  Objective-C programmers may have used nil to return an object from a method, with nil meaning “the absence of a valid object.” This works for objects but not well for structures, basic C types, or enumeration values. Objective-C methods typically return a special value, like NSNotFound indicating the absence of a valid object. This assumes that the method’s caller knows the special value to test against. Optionals indicate the absence of a value for any type at all, without using special constants.

The Integer Int() initializer might fail to return a value, so the method returns an optional Int, rather than an Int. Again, the question mark indicates that the value it contains is optional, meaning that it might contain some Int value, or it may contain no value at all. The value is either some Int or is nothing at all.

Swift’s nil is not the same as nil in Objective-C. With Objective-C, nil is a pointer to a nonexistent object. In Swift, nil is not a pointer; it is the absence of a value. Optionals of any type can be set to nil, not just object types.

In Chapter 4, you will learn how to unwrap optionals and check for the object of a valid object.

Using Variables in Playgrounds

Now that you have learned about data types, let’s write your code in a playground that adds two numbers and displays the sum.

  1. Open Xcode and select “Get started with a playground,” as shown in Figure 3-4.

    9781484214893_Fig03-04.jpg

    Figure 3-4. Creating a playground

  2. Name your playground DataTypes, as shown in Figure 3-5. Press next and select a directory to save your playground.

    9781484214893_Fig03-05.jpg

    Figure 3-5. Naming your playground

  3. When your playground is created, two lines of code are already placed in your code for you, as shown in Figure 3-6.

    9781484214893_Fig03-06.jpg

    Figure 3-6. Two lines of code

  4. Enter the code of this playground, as shown in Listing 3-3.

Your playground should look like Figure 3-7.

9781484214893_Fig03-07.jpg

Figure 3-7. Playground displaying the results of your Swift app

One of the neat features of playgrounds is that as you type in your code, Swift executes the line of code as you enter it so you can immediately view the results.

The // used in Swift programming enables programmers to make comments about their code. Comments are not compiled by your applications and are used as notes for the programmer or, more importantly, for programmers who follow the original developer. Comments help both the original developer and later developers understand how the app was developed.

Sometimes, it is necessary for comments to span several lines or just part of a line. This can be accomplished with /* and */. All the text between /* and */ is treated as comments and is not compiled.

print is a function that can take one parameter and print its contents.

Note  If your editor doesn’t have the same menus or gutter (the left column that contains the line numbers of the program) you saw in the previous screenshots, you can turn these settings on in Xcode preferences. You can open Xcode preferences by clicking the Xcode menu in the menu bar and then selecting Preferences.

Summary

In this chapter, you learned how data is used by your apps. You saw how to initialize variables and how to assign data to them. We explained that when variables are declared, they have a data type associated with them and that only data of the same type can be assigned to variables. The differences between variables and constants was also discussed, and we also introduced optionals.

Exercises

  • Write code within a Swift playground that multiplies two integers and displays the result.
  • Write code within a Swift playground that squares a float. Display the resulting float.
  • Write code within a Swift playground that subtracts two floats, with the result being stored as an integer. Note that rounding does not occur.
..................Content has been hidden....................

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