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.
![../images/341013_5_En_3_Chapter/341013_5_En_3_Fig1_HTML.jpg](../images/341013_5_En_3_Chapter/341013_5_En_3_Fig1_HTML.jpg)
Apple’s proprietary A12 Bionic processor
Moore’s Law
The number of transistors within 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 60 years.
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 eight bits. 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.
The Number 71 Represented As a Byte (64 + 4 + 2 + 1)
Power of 2 | 27 | 26 | 25 | 24 | 23 | 22 | 21 | 20 |
---|---|---|---|---|---|---|---|---|
Value for “on” bit | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
Actual bit | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 1 |
The Number 22 Represented As a Byte (16 + 4 + 2)
Power of 2 | 27 | 26 | 25 | 24 | 23 | 22 | 21 | 20 |
---|---|---|---|---|---|---|---|---|
Value for “on” bit | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
Actual bit | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 0 |
The Number 255 Represented As a Byte (128 + 64 + 32 + 16 + 8 + 4 + 2 + 1)
Power of 2 | 27 | 26 | 25 | 24 | 23 | 22 | 21 | 20 |
---|---|---|---|---|---|---|---|---|
Value for “on” bit | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
Actual bit | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
The Number 0 Represented As a Byte
Power of 2 | 27 | 26 | 25 | 24 | 23 | 22 | 21 | 20 |
---|---|---|---|---|---|---|---|---|
Value for “on” bit | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
Actual bit | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
Hexadecimal
Often, it will be necessary to represent characters in another format that is recognized by computers, namely, the hexadecimal format. The hex format is simply a “compressed” version of binary, where instead of eight characters used to represent a byte (eight bits), you can use two characters, for example, 00 or 2A or FF. 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. You may want to play with the Mac Calculator application in Programmer mode to see how hex relates to decimal and binary.
![../images/341013_5_En_3_Chapter/341013_5_En_3_Fig2_HTML.jpg](../images/341013_5_En_3_Chapter/341013_5_En_3_Fig2_HTML.jpg)
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 one-byte character set, Unicode can have up to a four-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. The “8” is how many bits are used per character, so it’s one byte per character, like ASCII.
As an iPhone developer, you will probably use this character encoding the most.
Data Types
Now that we’ve discussed how computers store 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.”
Mixing data types will cause either compiler warnings or compiler errors, and your app will not run.
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 after they have been initialized, but variables can be changed as many times as needed.
There are two ways to declare constant and variable types: explicitly and implicitly.
However, declaring the type is often unnecessary. Declaring the type implicitly shortens the code and makes it easier to type and ultimately maintain.
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.
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 Objective-C iOS developers, this concept is new. Optionals are not a hard topic to understand, but they take some time to get used to.
A variable may or may not have a value assigned to it.
Converting a String to an Integer
Unable to Convert a String to an Integer
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 presence of a valid object.
Using Variables in Playgrounds
- 1.Open Xcode and select “Get started with a playground,” as shown in Figure 3-3.Figure 3-3
Creating a playground
- 2.Select a Blank iOS template and click Next, as shown in Figure 3-4. Finally, name your playground DataTypes and click Create.Figure 3-4
Selecting a Blank iOS playground template
- 3.When your playground is created, two lines of code are already placed in your code for you, as shown in Figure 3-5.Figure 3-5
Two lines of code
- 4.
Add the code to this playground, as shown in Listing 3-3.
Playground Adding
![../images/341013_5_En_3_Chapter/341013_5_En_3_Fig6_HTML.jpg](../images/341013_5_En_3_Chapter/341013_5_En_3_Fig6_HTML.jpg)
Playground displaying the results of your Swift code
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) that you saw in the previous screenshots, you can turn these settings in Xcode preferences. You can open Xcode preferences by clicking the Xcode menu in the menu bar and then selecting Preferences. See Figure 3-7.
![../images/341013_5_En_3_Chapter/341013_5_En_3_Fig7_HTML.jpg](../images/341013_5_En_3_Chapter/341013_5_En_3_Fig7_HTML.jpg)
Adding line numbers to the gutter
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 were also discussed, and we also introduced optionals.
In the next chapter, we will be exploring how to use Boolean logic to control the flow of data within your apps.
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.