第一章,必備編程基礎和背景知識----Swift Apprentice中文版

? ? ? ? 本章簡介代碼的基礎支持,代碼運行的基本原理和swfit編程工具。

電腦工作原理簡介:

? ? ? ?其實電腦并沒有大家想象的那么強大,他的強大之處在于使用他的人,通過聰明的合理的方式組織他的計算能力,從而實現強大的功能更。并且計算機也簡單到爆,他的核心是cpu,cpu是用來做各種數字處理的核心單元,他的主要工作就是加減乘除操作,只是他的計算能力有點強大,每秒鐘能計算幾億次。

CPU直接處理的數據一般是通過寄存器進行存取,這是cpu可以直接操作的器件,他的特點是速度快,安全性高,缺點是容量小。當CPU處理的數據沒有在寄存器中時,他回去RAM,就是我們常說的內存里面取。同時會將結果緩存的寄存器,合適的時間再放回到內存中。原文中的圖和描述都有點簡單,沒有考慮一級緩存,二級緩存還有磁盤的情況,大家僅做參考。

? ? ? ? CPU不停從寄存器或者內存讀取指令,然后做各種加減乘除運算,最后再把結果放到寄存器和內容中,軟件就是這些指令的集合。軟件通過這些指令可以讓大家上網聊天把妹子,一個軟件的指令數量是非常驚人的。

? ? ? ? 軟件的生成需要編程語言和編譯工具。比如本文介紹的swift就是一種編程語言,通過電腦上的編譯工具,你寫的代碼會被翻譯成CPU能夠理解并執行的指令。一條編程語言的代碼可能會被編譯器翻譯成很多條指令,有的甚至可能會變成成百上千條指令。

數字的表示方式:?

? ? ? ? 數字之于CPU處理器正如面包和牛奶之于我們。CPU能處理的就是數字,因此我們的軟件和軟件要處理的對象全部都是數字,我們看到的文本是數字,看到的圖片也是由成千上萬的數字表示的,圖片上的每一個點叫做像素,一個像素有紅綠藍三色組成:純紅色就用 100%紅,0%綠, 0%藍這些數字表示,每個像素都有這些數字表示,所有像素按照一定的順序保存起來就能夠精確描述一張電子照片。

? ? ? ? 但是計算機中的數字表示方式與我們日常生活中使用的數字表示方式完全不是一回事兒,在我們生活中,我們使用的都是10進制的表示方式,比如432就是表示4百3十2:

每一位數字都是后面數字的10倍,這是我們通常生活中使用數字的方式:

? ? ? ? ? ? ?(0*1000) + (4*100) + (2*10) + (3*1) =423

二進制數字:

對應于10進制數字表達方式,2進制數字是以2為基礎:


? ? ? ? (1*8) + (1*4) + (0*2) + (1*1) =13

? ? ? ? 其中8= 2的3次方 4=2的2次方, 2 = 2的一次方, 1 = 2的0次方,對應于十進制的表達方式中,1000 = 10的3次方, 100 = 10的2次方, 10 = 10的一次方 1 = 10的0次方。通過此對應關系,你就可以理解什么是10進制表示,什么是2進制表示。

位數

? ? ? ? ?計算機除了表示數字的方式和日常生活不一樣外,它能夠表示的數字的長度也是有限制的,比如上圖中,為了表示13 這個數字,我們使用4個位表示,第一個權重是8的位,值是1,第二個權重是4的值是1 ,第三個權重是2的值是0, 最后一個權重是1,值也是1.這個4個位我們就說他是4個二進制位,或者4個比特位。因為計算機內存的限制,所有數字的表示全都用統一的位數長度,32比特位或者64比特位。

16進制:

? ? ? ? 與2進制相同,16進制表示的每一位的權重是16,但是因為我們日常生活中使用的阿拉伯數字一位數字最大是9,所以計算機系統是一個字母來表示超出9的值:

? ? ? ? ?a=10? ? ?b=11? ? ?c=12? ? ?d=13? ? ?e=14? ? ?f=15

因此他每一位的權重就會比較大,類似于2進制的表示,16進制的表示如上圖:

4096 = 16的3次方 , 256=16的2次方,? 16 = 16的1次方, 1 = 16的0次方。

上面數字換算成10進制的數值應該是:

(12*4096) + (0*256) + (13*16) + (14*1) =49374

code的工作原理:

計算機是大廚,code就是菜譜,而數據就是食材。下面以打印圖片為例:

第一步:從磁盤價值圖片

第二步: 調整圖片的大小為400*300

第三步:在圖片上加點點綴

第四步:打印圖片。

? ? ? ? ? 以上就是一種code,就是一種程序,一堆動作列表,只是上面的code無法直接編譯執行,因為還沒有這樣的編譯器可以理解上面這段指令的意義,不過隨著人工智能的發展,以后會出現這樣的編程方式,就是輸入一堆介于人類語言和計算機執行程序之間的code,然后人工智能機器人就會將上面的一堆動作列表轉換為計算機可以理解并執行的指令。

? ? ? ? 顯然現在還沒有出現這種編程方式,而swift也不具備這樣的能力。但是swift已經汲取以前古老語言的優勢,并避免了舊的編程語言的缺點。相對來說,swift是相對比較高級和現代的編程方式。最近在看資料的時候,發現大部分demo和程序都是用swift編寫,因此這是我為什么會翻譯這本書的原因,編程語言在更新,我們編程人員也需要跟新只是。就像我說的,有一天人工智能會理解近似人類自然語言的編程代碼,那個時候,swift也會成為我們所說的古老語言,而我們大多數人只需要簡單的學習就能夠實現輕松的編程。彼時我們這樣的程序員就會像是現在的補鞋補鍋匠,雖然也是一門技術,但用途不多了。

開發工具----Playground

? ? ? ?編寫code的工具一般叫做IDE(集成開發工具),這個工具會有一整套的軟件,將你編寫的代碼轉換為可以執行的,計算機能理解的指令集合,就是軟件。

? ? ? ? swift的編程工具之一是XCode,這個IDE有一個Playground功能,可以在不用編譯的情況下產看代碼執行結果,我們之前講過,代碼需要編譯器解釋成CPU理解的質量才能夠執行,而這個地方所謂的無需編譯就能夠查看代碼又是什么呢?其實在高級編程語言中,沒有那種代碼不需要解釋編譯就能夠執行,這里所謂的需要編譯,只是xcode做了很多實時編譯和解釋,讓你無需單獨再執行一遍編譯過程而已。

創建一個Playground:

創建之前,你首先要下載Xcode這個IDE。打開XCODE之后你應該能夠看到這個界面。

如果沒有顯示,說明你在設置中將這個界面修改為啟動不顯示了。產看這個界面的辦法是:Command-Shift-1

或者是 菜單欄中Window-->Welcome to Xcode.

在這個界面中,從左邊選擇"Get started with a playground",就是圖中第一個選項。接著會顯示新界面:

按照如圖選擇,然后next會提示你工程的保存路徑和工程名。設置完畢之后顯示下面的界面

區域1-代碼區:這就是我們需要編寫swift代碼的地方

區域2-結果區:代碼運行結果的顯示的區域

區域3-是否是自動編譯運行的按鈕開關,如果打開,區域2會自動執行區域1的代碼。

區域4-自動運行狀態,如果代碼還在編譯執行,那這個地方會有等待提示。

區域5-面板顯示控制,這個按鈕可以控制左邊,下面,和右邊的三個面板是否顯示。你可以選擇點擊一下,看看這三個面板分別顯示設什么內容。

如果你的XCode的代碼區沒有顯示代碼的行號,你可以通過這個地方進行設置。Xcode->

小結:

計算機的本身只能做簡單的數學運算

編程語言允許你編寫代碼,然后代碼生成計算機可以理解并執行的程序

CPU處理的是2進制的數據

我們學習Swift的開發工具是XCode

Playground這個功能可以讓我們快速查看代碼的執行效果。



Welcome to our book! In this first chapter, you’re going to learn a few basics. You’ll

learn how the code works first. Then you’ll learn about the tools you’ll be using to write

Swift code.

How a computer works

You may not believe me when I say it, but a computer is not very smart on its own.

The power of computers is all derived from how they’re programmed by people like

you and me. If you want to successfully harness the power of a computer — and I

assume you do if you’re reading this book — it’s important to understand how

computers work.

It may also surprise you to learn that computers themselves are rather simple

machines. At the heart of a computer is a Central Processing Unit(CPU). This is

essentially a math machine. It performs addition, subtraction, and other

arithmetical operations on numbers. Everything you see when you operate your

computer is all built upon a CPU crunching numbers many millions of times per

second. Isn’t it amazing what can come from just numbers?



The CPU stores the numbers it acts upon in small memory units called registers.

The CPU is able to read numbers into registers from the computer’s main memory,

known as Random Access Memory(RAM). It’s also able to write the number

stored in a register back into RAM. This allows the CPU to work with large amounts

of data that wouldn’t all fit in the bank of registers.

Here is a diagram of how this works:



As the CPU pulls values from RAM into its registers, it uses those values in its math

unit and stores the results back in another register.

Each time the CPU makes an addition, a subtraction, a read from RAM or a write to

RAM, it’s executing a single instruction. Each computer program is usually made

up of thousands to millions of instructions. A complex computer program such as

your operating system, macOS (yes, that’s a computer program too!), may have

many millions of instructions in total.

It’s entirely possible to write individual instructions to tell a computer what to do,

but for all but the simplest programs, it would be immensely time-consuming and

tedious. This is because most computer programs aim to do much more than simple

math — computer programs let you surf the Internet, manipulate images, and allow

you to chat with your friends.

Instead of writing individual instructions, you write code in a specific programming language, which in your case will be Swift. This code is put through

a computer program called a compiler, which converts the code into instructions

the CPU knows how to execute. Each line of code you write will turn into many

instructions — some lines could end up being tens of instructions!

Representing numbers

As you know by now, numbers are a computer’s bread and butter, the fundamental

basis of everything it does. Whatever information you send to the compiler will

eventually become a number. For example, each character within a block of text is

represented by a number. You’ll learn more about this in Chapter 3, which delves

into types including strings, the computer term for a block of text.

Images are no exception. In a computer, each image is also represented by a series

of numbers. An image is split into many thousands, or even millions, of picture

elements called pixels, where each pixel is a solid color. If you look closely at your

computer screen, you may be able to make out these blocks. That is unless you

have a particularly high-resolution display where the pixels are incredibly small!

Each of these solid color pixels is usually represented by three numbers: one for the

amount of red, one for the amount of green and one for the amount of blue. For

example, an entirely red pixel would be 100% red, 0% green and 0% blue.

The numbers the CPU works with are notably different from those you are used to.

When you deal with numbers in day-to-day life, you work with them in base 10,

otherwise known as the decimal system. Having used this numerical system for so

long, you intuitively understand how it works. So that you can you can appreciate

the CPU’s point of view, consider how base 10 works.

The decimal or base 10 number 423 contains three units, two tens and four

hundreds:


In the base 10 system, each digit of a number can have a value of 0, 1, 2, 3, 4, 5,

6, 7, 8 or 9, giving a total of 10 possible values for each digit. Yep, that’s why it’s

called base 10!

But the true value of each digit depends on its position within the number. Moving

from right to left, each digit gets multiplied by an increasing power of 10. So the

multiplier for the far-right position is 10 to the power of 0, which is 1. Moving to the

left, the next multiplier is 10 to the power of 1, which is 10. Moving again to the

left, the next multiplier is 10 to the power of 2, which is 100. And so on.

This means each digit has a value ten times that of the digit to its right. The

number423is equal to the following:

(0*1000) + (4*100) + (2*10) + (3*1) =423Binary numbers

Because you’ve been trained to operate in base 10, you don’t have to think about

how to read most numbers — it feels quite natural. But to a computer, base 10 is

way too complicated! Computers are simple-minded, remember? They like to work

with base 2.

Base 2is often called binary, which you’ve likely heard of before. It follows that

base 2 has only two options for each digit: 0 or 1.

Almost all modern computers use binary because at the physical level, it’s easiest

to handle only two options for each digit. In digital electronic circuitry, which is

mostly what comprises a computer, the presence of an electrical voltage is 1 and

the absence is 0 — that’s base 2!

Here’s a representation of the base 2 number 1101:


In the base 10 number system, the place values increase by a factor of 10: 1, 10,

100, 1000, etc. In base 2, they increase by a factor of 2: 1, 2, 4, 8, 16, etc. The

general rule is to multiply each digit by an increasing power of the base number —

in this case, powers of 2 — moving from right to left.

So the far-right digit represents (1 * 2^0), which is (1 * 1), which is 1. The next

digit to the left represents (0 * 2^1), which is (0 * 2), which is 0. In the illustration

above, you can see the powers of 2 on top of the blocks.

Put another way, every power of 2 either is (1) or isn’t (0) present as a component

of a binary number. The decimal version of a binary number is the sum of all the

powers of 2 that make up that number. So the binary number 1101 is equal to:

(1*8) + (1*4) + (0*2) + (1*1) =13

And if you wanted to convert the base 10 number 423 into binary, you would simply

need to break down 423 into its component powers of 2. You would wind up with

the following:

As you can see by scanning the binary digits in the above equation, the resulting

binary number is 110100111. You can prove to yourself that this is equal to 423 by

doing the math!

The computer term given to each digit of a binary number is abit(a contraction of

“binary digit”). Eight bits make up abyte. Four bits is called anibble, a play on

words that shows even old school computer scientists had a sense of humor.


A computer’s limited memory means it can normally deal with numbers up to a

certain length. Each register, for example, is usually 32 or 64 bits in length, which is

why we speak of 32-bit and 64-bit CPUs.

Therefore, a 32-bit CPU can handle a maximum base-number of 4,294,967,295,

which is the base 2 number11111111111111111111111111111111. That is 32 ones—

count them!

It’s possible for a computer to handle numbers that are larger than the CPU

maximum, but the calculations have to be split up and managed in a special and

longer way, much like the long multiplication you performed in school.

Hexadecimal numbers

As you can imagine, working with binary numbers can become quite tedious,

because it can take a long time to write or type them. For this reason, in computer

programming, we often use another number format known ashexadecimal, orhexfor short. This isbase 16.

Of course, there aren’t 16 distinct numbers to use for digits; there are only 10. To

supplement these, we use the first six letters,athroughf. They are equivalent to

decimal numbers like so:

?a=10

?b=11

?c=12

?d=13

?e=14

?f=15

Here’s a base 16 example using the same format as before:


Notice first that you can make hexadecimal numbers look like words. That means

you can have a little bit of fun. :]

Now the values of each digit refer to powers of 16. In the same way as before, you

can convert this number to decimal like so:

(12*4096) + (0*256) + (13*16) + (14*1) =49374

You translate the letters to their decimal equivalents and then perform the usual

calculations.

But why bother with this?

Hexadecimal is important because each hexadecimal digit can represent precisely

four binary digits. The binary number1111is equivalent to hexadecimalf. It follows

that you can simply concatenate the binary digits representing each hexadecimal

digit, creating a hexadecimal number that is shorter than its binary or decimal

equivalents.

For example, consider the numberc0defrom above:

This turns out to be rather helpful, given how computers use long 32-bit or 64-bit

binary numbers. Recall that the longest 32-bit number in decimal is 4,294,967,295.

In hexadecimal, it isffffffff. That’s much more compact and clear.

How code works

Computers have a lot of constraints, and by themselves, they can only do a small

number of things. The power that the computer programmer adds, through coding,

is putting these small things together, in the right order, to produce something

much bigger.

Coding is much like writing a recipe. You assemble ingredients (the data) and give

the computer a step-by-step recipe for how to use them.

Here’s an example:

c = 1100

0 = 0000

d = 1101

e = 1110

c0de = 1100 0000 1101 1110

Step 1. Load photo from hard drive.

Step 2. Resize photo to 400 pixels wide by 300 pixels high.

Step 3. Apply sepia filter to photo.

Step 4. Print photo.

This is what’s known aspseudo-code. It isn’t written in a valid computer

programming language, but it represents thealgorithmthat you want to use. In

this case, the algorithm takes a photo, resizes it, applies a filter and then prints it.

It’s a relatively straightforward algorithm, but it’s an algorithm nonetheless!


Swift code is just like this: a step-by-step list of instructions for the computer.

These instructions will get more complex as you read through this book, but the

principle is the same: You are simply telling the computer what to do, one step at a

time.

Each programming language is a high-level, pre-defined way of expressing these

steps. The compiler knows how to interpret the code you write and convert it into

instructions that the CPU can execute.

There are many different programming languages, each with its own advantages

and disadvantages. Swift is an extremely modern language. It incorporates the

strengths of many other languages while ironing out some of their weaknesses. In

years to come, we’ll look back on Swift as being old and crusty, too. But for now,

it’s an extremely exciting language because it is quickly evolving.

This has been a brief tour of computer hardware, number representation and code,

and how they all work together to create a modern program. That was a lot to

cover in one section! Now it’s time to learn about the tools you’ll use to write in

Swift as you follow along with this book.

Playgrounds

The set of tools you use to write software is often referred to as thetoolchain. The

part of the toolchain into which you write your code is known as theIntegrated

Development Environment(IDE). The most commonly used IDE for Swift is

called Xcode, and that’s what you’ll be using.

Xcode includes a handy feature called aPlayground, which allows you to quickly

write and test code without needing to build a complete app. You’ll use playgrounds

throughout the book to practice coding, so it’s important to understand how they

work. That’s what you’ll learn during the rest of this chapter.

Creating a playground

When you open Xcode, it will greet you with the following welcome screen:


If you don’t see this screen, it’s most likely because the “Show this window when

Xcode launches” option was unchecked. You can also open the screen by pressingCommand-Shift-1or clickingWindow\Welcome to Xcodefrom the menu bar.

From the welcome screen, you can jump quickly into a playground by clicking onGet started with a playground. Click on that now and Xcode will take you to a

new screen:


From here, you can name the playground and select your desired platform. The

name is merely cosmetic and for your own use; when you create your playgrounds,

feel free to choose names that will help you remember what they’re about. For

example, while you’re working through Chapter 2, you may want to name your

playgroundChapter2.

The second option you can see here is the platform. Currently, this can be eitheriOS,macOSortvOS.

The platform you choose simply defines which template Xcode will use to create the

playground. Each platform comes with its own environment set up and ready for

you to begin playing around with code. For the purposes of this book, choose

whichever you wish. You won’t be writing any platform-specific code; instead, you’ll

be learning the core principles of the Swift language.

Once you’ve chosen a name and a platform, click onNextand then save the

playground. Xcode then presents you with the playground, like so:


New playgrounds don’t start entirely empty but have some basic starter code to get

you going. Don’t worry — you’ll soon learn what this code means.

Playgrounds overview

At first glance, a playground may look like a rather fancy text editor. Well, here’s

some news for you: It is essentially just that!


The above screenshot highlights the first and most important things to know about:

1.Sourceeditor:Thisistheareainwhichyou’llwriteyourSwiftcode.It’smuch

like a text editor such as Notepad or TextEdit. You’ll notice the use of what’s

known as a monospace font, meaning all characters are the same width. This

makes the code much easier to read and format.

2.Resultssidebar:Thisareashowstheresultsofyourcode.You’lllearnmore

about how code is executed as you read through the book. The results sidebar

will be the main place you’ll look to confirm your code is working as expected.

3.Executioncontrol:Playgroundsexecuteautomaticallybydefault,meaningyou

can write code and immediately see the output. This control allows you to

execute the playground again. Holding down the button allows you to switch

between automatic execution and manual execution modes.

4.Activityviewer:Thisshowsthestatusoftheplayground.Inthescreenshot,it

shows that the playground has finished executing and is ready to handle more

code in the source editor. When the playground is executing, this viewer will

indicate this with a spinner.

5.Panel controls: These toggle switches show and hide three panels,one that

appears on the left, one on the bottom and one on the right. The panels each

display extra information that you may need to access from time to time. You’ll

usually keep them hidden, as they are in the screenshot. You’ll learn more

about each of these panels as you move through the book.

Playgrounds execute the code in the source editor from top to bottom. Every time

you change the code, the playground will re-execute everything. You can also force

a re-execution by clickingEditor\Execute Playground. Alternatively, you can use

the execution control.

You can turn on line numbers on the left side of the source editor by clickingXcode

\Preferences...\Text Editing\Line Numbers. Line numbers can be very useful

when you want to refer to parts of your code.

Once the playground execution is finished, Xcode updates the results sidebar to

show the results of the corresponding line in the source editor. You’ll see how to

interpret the results of your code as you work through the examples in this book.

Key points

Computers, at their most fundamental level, perform simple mathematics.

A programming language allows you to write code, which the compiler converts

into instructions that the CPU can execute.

Computers operate on numbers in base 2 form, otherwise known as binary.

The IDE you use to write Swift code is named Xcode.

By providing immediate feedback about how code is executing, playgrounds allow

you to write and test Swift code quickly and efficiently.

Where to go from here?

If you haven’t done so already, open Xcode for yourself and create your first

playground. Give it the nameChapter01and use the iOS platform. Save it

somewhere on your hard drive and you’ll end up with an open playground.

Now you’re all set to follow along with the next chapter!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容