第一章,必备编程基础和背景知识----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!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容