注釋:
? ? ? ? 注釋始終特殊的代碼,他并不會被編譯器解釋為CPU可以理解的二進制指令,而是代碼作者解釋給其他作者或者瀏覽者的人類的語言。是對自己代碼功能的一種解釋。
單行注釋:? "'//" 比如:// This is a comment. It is not executed.
多行注釋一:? 多個"http://"
? ? ? ? ? ? ? ? ? ?// This is also a comment.
? ? ? ? ? ? ? ? ? ? // Over multiple lines.
多行注釋二:? ? ?以 /*開頭, 以*/結(jié)尾
? ? ? ? ? ? ? ? ? /* This is also a comment.
? ? ? ? ? ? ? ? ?Over many...
? ? ? ? ? ? ? ? ?many...
? ? ? ? ? ? ? ?many lines. */
打印輸出:
print("Hello, Swift Apprentice reader!")
在創(chuàng)建的工程中輸入以上代碼,就會將內(nèi)容打印到控制臺。

數(shù)學運算:
基本的運算加減乘除的表示方式如下:

這里需要注意的是,Swift語言與其他編程語言的語法差別,空格居然是個敏感詞,在操作符的前后,要么都有空格,要么都沒有,否則就會報錯:
2+6// OK
2+6// OK
2+6// ERROR
2+6// ERROR
這大概是這一小節(jié)里面唯一值得說明一下的內(nèi)容了。
小數(shù):
小數(shù)需要注意的就是參與運算的數(shù)字的類型,遵循的原則就是:運算結(jié)果的類型與參與運算的數(shù)字中精度最高的數(shù)字的類型相同,這個再英文版中描述的不是很清楚。我把例子列出來。
27 / 7 = 3? ?結(jié)果是3,因為參與運算的兩個數(shù)字都是整數(shù),所以結(jié)果也是整數(shù),不是4舍5入,只是取結(jié)果中的整數(shù)部分.
以下三種情況的結(jié)果都是? ? 3.857142857142857。因為參與運算的雙方至少有一個數(shù)是小數(shù)。所以結(jié)果按照小數(shù)來處理,當然這個小數(shù)還涉及到計算機能表達的精度問題,不同類型的計算機能表的小數(shù)的精度也不一樣。 所謂的精度,比如三分之一這個數(shù)字在計算機中的表示就不可能小數(shù)點之后有無窮多個3,只能是在表達能力范圍以內(nèi)盡可能的接近真實值。這個接近程度指的就是精度。
27/7.0
27.0/7
27.0/7.0
取模:
這個操作指的就是除法中的余數(shù),小學問題不解釋,取模的運算符號為:%。這里需要注意的是,原文并沒有提及參與取模的必須是整數(shù), 否則就會報錯。這是個又去的問題,如果你是名java程序員,你可以試驗一下,對兩個float類型的數(shù)取模,編譯器會怎么處理,運算結(jié)果又是什么。在playground中運行會報錯:
error: '%' is unavailable: Use truncatingRemainder instead?27.0 % 7
位移:
? ? ? ? 位移指的是將數(shù)字的二進制形式進行比特位的轉(zhuǎn)換,分為左移和右移。其實這個話題不適合做這么簡單的介紹,因為移動還和計算機的長度有關(guān)系,如果移動太多超出計算機的表達長度,比如之前的提到的32bit和64bit的cpu。他們只能一次表示一個32(64)個bit位的數(shù)字,如果把15這個數(shù)字左移動32位,你看一下結(jié)果和預(yù)想的完全不一樣。在這里不糾結(jié)這個問題,在正常情況下,左移就是乘以2,右移就是除以2。位移的好處就是對于cpu來說,這個操作需要消耗的時間少一些。
? ? ? ? 記得有位大神卡馬克,編寫的3D游戲引擎。里面有很多用位移來取代復(fù)雜數(shù)學函數(shù)的代碼,當年學習很久,有些到現(xiàn)在還沒整明白,據(jù)說有位大學教授專門寫論文,論證了里面一個數(shù)學常數(shù)對于計算機進行數(shù)學函數(shù)運算的優(yōu)勢,數(shù)學函數(shù)運算包含正弦,余弦,開平方等操作。

預(yù)算符號的優(yōu)先級:
這也是小學問題,不糾結(jié):350/5+2 = 72? ?而? ? 350/ (5+2)? = 50
數(shù)學函數(shù):
swift 提供了很多數(shù)學運算的函數(shù),這些函數(shù)有些不是操作系統(tǒng)本來就有的。其中包含一些三角函數(shù),開平方運算和取大小值:
sin(45*Double.pi /180)? ? ? ? ? ? ? ? // 0.7071067811865475
cos(135*Double.pi /180)? ? ? ? ? ? // -0.7071067811865475
sqrt(2.0)? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?// 1.414213562373095
max(5,10)? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?// 10
min(-5, -10)? ? ? ? ? ? ? ? ? ? ? ? ? ? ? // -10
max(sqrt(2.0),Double.pi /2)? ? ?// 1.570796326794897
為數(shù)據(jù)命名:
從這開始才算是這是開始Swift預(yù)言的學習,
? ? ? ? 為常量命名: let? number:Int=10 ,定義一個Int類型的常數(shù)number,初始化值為10.這個number的值一旦出事化,以后就無法再賦值,如果執(zhí)行 number = 12 這類操作,會直接報錯,因為這是常量,常量的意思就是一旦初始化就不再改變的量。
? ? ? ? 變量:var? variableNumber:Int=42 定義一個Int類型,值為42的變量 variableNumber,你可以再隨后的操作中修改這個變量的值。 例如 再次賦值 variableNumber = 12;下面這個操作很有意思:variableNumber=1_000_000? ?此時變量的值為1000000,這應(yīng)該是方便土豪去數(shù)零方便,這個語法在別的語言應(yīng)該少見吧。
? ? ? ? ? 命名規(guī)則:其實每個人都有自己的命名愛好,只是swift略拽的地方是,可以用unicode字符作為變量的名字:

自增與自減操作:
var counter = 0;
counter += 1與counter = counter + 1等價運算
counter *= 1與counter = counter * 1等價運算
counter -= 1與counter = counter - 1等價運算
counter /= 1與counter = counter / 1等價運算
小結(jié):本節(jié)講解的是基礎(chǔ)的數(shù)字命名及運算,需要注意的是,如果你是從別的語言轉(zhuǎn)學Swift,本節(jié)中需要注意的是2點:??
1.操作符前后要么有空格,要么沒有空格
2.變量名可以是Unicode并且取模的運算只能交給Int類型數(shù)據(jù)參與,其他類型數(shù)據(jù)取模操作會出錯。
Now that you know how computers interpret the code you write and what tools
you’ll be using to write it, it’s time to begin learning about Swift itself.
In this chapter, you’ll start by learning some basics such as code comments,
arithmetic operations, constants, and variables. These are some of the fundamental
building blocks of any language, and Swift is no different.
Code comments
The Swift compiler generates executable code from your source code. To accomplish
this, it uses a detailed set of rules you will learn about in this book. Sometimes
these details can obscure the big picture of why?these details can obscure the big picture of why you wrote your code a certain way
or even what problem you are solving. To prevent this, it’s good to document what
you wrote so that the next human who passes by will be able to make sense of your
work. That next human, after all, maybe a future you.
Swift, like most other programming languages, allows you to document your code
through the use of what are called comments. These allow you to write any text
directly alongside your code which is ignored by the compiler.
The first way to write a comment is like so:
// This is a comment. It is not executed.
This is a single line comment. You could stack these up like so to allow you to
write paragraphs:
// This is also a comment.
// Over multiple lines.
However, there is a better way to write comments which span multiple lines. Like
so:
/* This is also a comment.
Over many...
many...
many lines. */
This is a multi-line comment. The start is denoted by/*and the end is denoted
by*/. Simple!
You should use code comments where necessary to document your code, explain
your reasoning, or simply to leave jokes for your colleagues :].
Printing out
It’s also useful to see the results of what your code is doing. In Swift, you can
achieve this through the use of the print command.
print will output whatever you want to the debug area(sometimes referred to as
the console).
For example, consider the following code:
print("Hello, Swift Apprentice reader!")
This will output a nice message to the debug area, like so:

You can hide or show the debug area using the button highlighted with the red box
in the picture above. You can also clickView\Debug Area\Show Debug Area to
do the same thing.
Arithmetic operations
When you take one or more pieces of data and turn them into another piece of
data, this is known as an operation.
The simplest way to understand operations is to think about arithmetic. The
addition operation takes two numbers and converts them into the sum of the two
numbers. The subtraction operation takes two numbers and converts them into the
difference of the two numbers.
You’ll find simple arithmetic all over your apps; from tallying the number of “l(fā)ikes”
on a post, to calculating the correct size and position of a button or a window,
numbers are indeed everywhere!
In this section, you’ll learn about the various arithmetic operations that Swift has to
offer by considering how they apply to numbers. In later chapters, you see
operations for types other than numbers.
Simple operations
All operations in Swift use a symbol known as the operator to denote the type of the operation they perform.
Consider the four arithmetic operations you learned in your early school days:
addition, subtraction, multiplication, and division. For these simple operations, Swift
uses the following operators:
? Add:+
? Subtract:-
? Multiply:*
? Divide:/
These operators are used like so:
2+6
10-2
2*4
24/3
Each of these lines is what is known as an expression. An expression has a value.
In these cases, all four expressions have the same value: 8. You write the code to
perform these arithmetic operations much as you would write it if you were using
pen and paper.

In your playground, you can see the values of these expressions in the right-hand
bar, known as the results sidebar, like so:

If you want, you can remove the white space surrounding the operator:
2+6
Removing the whitespace is an all or nothing, you can't mix styles. For example:
2+6// OK2+6// OK2+6// ERROR2+6// ERROR
It’s often easier to read expressions if you have white space on either side of the
operator.
Decimal numbers
All of the operations above have used whole numbers, more formally known as integers. However, as you will know, not every number is whole.
As an example, consider the following:
22/7
This, you may be surprised to know, results in the number 3. This is because if you
only use integers in your expression, Swift makes the result an integer also. In this
case, the result is rounded down to the next integer.
You can tell Swift to use decimal numbers by changing it to the following:
22.0/7.0
This time, the result is 3.142857142857143 as expected.
The remainder operation
The four operations you’ve seen so far are easy to understand because you’ve been
doing them for most of your life. Swift also has more complex operations you can
use, all of the standard mathematical operations, just less common ones. Let’s
turn to them now.
The first of these is the remainder operation, also called the modulo operation. In
division, the denominator goes into the numerator a whole number of times, plus a
remainder. This remainder is exactly what the remainder operation gives. For
example, 10 modulo 3 equals 1, because 3 goes into 10 three times, with a
the remainder of 1.
In Swift, the remainder operator is the%symbol, and you use it like so:
28%10
In this case, the result equals 8, because 10 goes into 28 twice with a remainder of
8.
Shift operations
The shift left and shift right operations take the binary form of a decimal number
and shift the digits left or right, respectively. Then they return the decimal form of
the new binary number.
For example, the decimal number 14 in binary, padded to 8 digits, is 00001110.
Shifting this left by two places results in 00111000, which is 56 in decimal.
Here’s an illustration of what happens during this shift operation:

The digits that come in to fill the empty spots on the right become0. The digits that
fall off the end on the left are lost.
Shifting right is the same, but the digits move to the right.The operators for these two operations are as follows:
? Shift left:<<
? Shift right:>>
These are the first operators you’ve seen that contain more than one character.
Operators can contain any number of characters, in fact.
Here’s an example that uses both of these operators:
1<<3
32>>2
Both of these values equal the number 8.
One reason for using shifts is to make multiplying or dividing by powers of two
easy. Notice that shifting left by one is the same as multiplying by two, shifting left
by two is the same as multiplying by four, and so on. Likewise, shifting right by one
is the same as dividing by two, shifting right by two is the same as dividing by four,
and so on.
In the old days, code often made use of this trick because shifting bits is much
simpler for a CPU to do than complex multiplication and division arithmetic.
Therefore the code was quicker if it used shifting. However these days, CPUs are
much faster and compilers can even convert multiplication and division by powers
of two into shifts for you. So you’ll see shifting only for binary twiddling, which you
probably won’t see unless you become an embedded systems programmer!
Order of operations
Of course, it’s likely that when you calculate a value, you’ll want to use multiple
operators. Here’s an example of how to do this in Swift:
((8000/ (5*10)) -32) >> (29%5)
Notice the use of parentheses, which in Swift serve two purposes: to make it clear
to anyone reading the code — including yourself — what you meant, and to
disambiguate. For example, consider the following:
350/5+2
Does this equal 72 (350 divided by 5, plus 2) or 50 (350 divided by 7)? Those of
you who paid attention in school will be screaming “72!” And you would be right!
Swift uses the same reasoning and achieves this through what’s known as operator precedence. The division operator (/) has a higher precedence than the
addition operator (+), so in this example, the code executes the division operation
first.
If you wanted Swift to do the addition first — that is, to return 50 — then you could
use parentheses like so:
350/ (5+2)
The precedence rules follow the same that you learned in math at school. Multiply
and divide have the same precedence, higher than add and subtract which also
have the same precedence.
Math functions
Swift also has a vast range of math functions for you to use when necessary. You
never know when you need to pull out some trigonometry, especially when you’re a
pro-Swift-er and writing those complex games!
Note: Not all of these functions are part of Swift. Some are provided by the
operating system. Don’t remove the import statement that comes as part of
the playground template or Xcode will tell you it can’t find these functions.
For example, consider the following:
sin(45*Double.pi /180)? ? ? ? // 0.7071067811865475
cos(135*Double.pi /180)? ? // -0.7071067811865475
These compute the sine and cosine respectively. Notice how both make use of Double.pi which is a constant Swift provides us, ready-made with pi to as much
precision as is possible by the computer. Neat!
Then there’s this:
Sqrt(2.0)? ? ? // 1.414213562373095
This computes the square root of 2. Did you know that sin(45°) equals 1 over the
square root of 2?
Note: Notice how you used2.0instead of2in the example above? Functions
that are provided by the operating systems (like sqrt, sin, and cos) are picky
and accept only numbers that contain a decimal point.
Not to mention these would be a shame:
max(5,10)// 10
min(-5, -10)// -10
These compute the maximum and minimum of two numbers respectively.
If you’re particularly adventurous you can even combine these functions like so:
max(sqrt(2.0),Double.pi /2)// 1.570796326794897
Naming data
At its simplest, computer programming is all about manipulating data. Remember,
everything you see on your screen can be reduced to numbers that you send to the
CPU. Sometimes you yourself represent and work with this data as various types of
numbers, but other times the data comes in more complex forms such as text,
images, and collections.
In your Swift code, you can give each piece of data a name you can use to refer to
it later. The name carries with it an associated type that denotes what sort of data
the name refers to, such as text, numbers, or a date.
You’ll learn about some of the basic types in this chapter, and you’ll encounter many
other types throughout the rest of this book.
Constants
Take a look at this:
let number:Int=10
This declares a constant called number which is of type int. Then it sets the value of
the constant to the number10.
The typeIntcan store integers. The way you store decimal numbers is like so:letpi: Double=3.14159
This is similar to the Int constant, except the name and the type are different. This
time, the constant is a Double, a type that can store decimals with high precision.
There’s also a type called Float, short for floating point, that stores decimals with
lower precision than Double. In fact, Double has about double the precision of Float,
which is why it’s called Double in the first place. A Float takes up less memory than
a Double but generally, memory use for numbers isn’t a huge issue and you’ll see Double used in most places.
Once you’ve declared a constant, you can’t change its data. For example, consider the following code:
let number:Int=10 number =0
This code produces an error:
Cannot assign to value: 'number' is a 'let' constant
In Xcode, you would see the error represented this way:

Constants are useful for values that aren’t going to change. For example, if you
were modeling an airplane and needed to keep track of the total number of seats
available, you could use a constant.
You might even use a constant for something like a person’s age. Even though their
age will change as their birthday comes, you might only be concerned with their
age at this particular instant.
Variables
Often you want to change the data behind a name. For example, if you were
keeping track of your bank account balance with deposits and withdrawals, you
might use a variable rather than a constant.
Note: Thinking back to operators, here’s another one. The equals sign,=, is
known as the assignment operator.
If your program’s data never changed, then it would be a rather boring program!
But as you’ve seen, it’s not possible to change the data behind a constant.
When you know you’ll need to change some data, you should use a variable to
represent that data instead of a constant. You declare a variable in a similar way,
like so:
var variableNumber:Int=42
Only the first part of the statement is different: You declare constants using let,
whereas you declare variables using var.
Once you’ve declared a variable, you’re free to change it to whatever you wish, as
long as the type remains the same. For example, to change the variable declared
above, you could do this:
varvariableNumber:Int=42
variableNumber =0
variableNumber =1_000_000?
To change a variable, you simply assign it a new value.
Note: In Swift, you can optionally use underscores to make larger numbers
more human-readable. The quantity and placement of the underscores are up to
you.
This is a good time to take a closer look at the results sidebar of the playground.
When you type the code above into a playground, you’ll see that the results sidebar
on the right shows the current value ofvariableNumberat each line:

The results sidebar will show a relevant result for each line if one exists. In the case
of a variable or constant, the result will be the new value, whether you’ve just
declared a constant, or declared or reassigned a variable.
Using meaningful names
Always try to choose meaningful names for your variables and constants. Good
names can act as documentation and make your code easy to read.
A good name specifically describes what the variable or constant represents. Here
are some examples of good names:
?personAge
?numberOfPeople
?gradePointAverage
Often a bad name is simply not descriptive enough. Here are some examples of bad
names:
?a
?temp
?average
The key is to ensure that you’ll understand what the variable or constant refers to
when you read it again later. Don’t make the mistake of thinking you have an
infallible memory! It’s common in computer programming to look back at your own
code as early as a day or two later and have forgotten what it does. Make it easier
for yourself by giving your variables and constants intuitive, precise names.
Also, note how the names above are written. In Swift, it is common to camel case names. For variables and constants, follow these rules to properly case your
names:
Start with a lowercase letter.
If the name is made up of multiple words, join them together and start every other word with an uppercase letter.
If one of these words is an abbreviation, write the entire abbreviation in the
same case (e.g.:sourceURL and urlDescription)
In Swift, you can even use the full range of Unicode characters. For example, you
could declare a variable like so:

That might make you laugh, but use caution with special characters like these. They
are harder to type and therefore may end up causing you more pain than
amusement.

Special characters like these probably make more sense in data that you store rather than in Swift code; you’ll learn more about Unicode in Chapter 4, “Strings.”
Increment and decrement
A common operation that you will need is to be able to increment or decrement a
variable. In Swift, this is achieved like so:
varcounter:Int=0counter +=1
// counter = 1
counter -=1// counter = 0
The counter variable begins as0. The increment sets its value to1, and then the
decrement sets its value back to0.
These operators are similar to the assignment operator (=), except they also
perform an addition or subtraction. They take the current value of the variable, add
or subtract the given value and assign the result to the variable.
In other words, the code above is shorthand for the following:
varcounter:Int=0counter = counter +1counter = counter -1
Similarly, the*=and/=operators do the equivalent for multiplication and division,
respectively:
varcounter:Int=10counter *=3// same as counter = counter * 3
// counter = 30
counter /=2// same as counter = counter / 2
// counter = 15
Mini-exercises
If you haven’t been following along with the code in Xcode, now’s the time to create
a new playground and try some exercises to test yourself!
DeclareaconstantoftypeIntcalledmyAgeandsetittoyourage.
DeclareavariableoftypeDoublecalledaverageAge.Initially, set it to your own
age. Then, set it to the average of your age and my own age of30.
CreateaconstantcalledtestNumberandinitializeitwithwhateverintegeryou’d
like. Next, create another constant calledevenOddand set it equal totestNumber modulo 2. Now changetestNumberto various numbers. What do you notice
aboutevenOdd?
4. Createavariablecalledanswerandinitializeitwiththevalue0.Incrementitby1. Add10to it. Multiply it by10. Then, shift it to the right by3. After all of these
operations, what’s the answer?
Key points
Code comments are denoted by a line starting with//or multiple lines
bookended with/*and*/.
Code comments can be used to document your code.
You can use print to write things to the debug area.
The arithmetic operators are:
Add: +Subtract: -Multiply: *Divide: /Remainder:%
Constants and variables give names to data.
Once you’ve declared a constant, you can’t change its data, but you can change
a variable’s data at any time.
Always give variables and constants meaningful names to save you and your
colleagues headaches later.
Operators to perform arithmetic and then assign back to the variable:
Add and assign: +=Subtractand assign: -=Multiplyand assign: *=Divideand assign: /=
Where to go from here?
In this chapter, you’ve only dealt with only numbers, both integers and decimals. Of
course, there’s more to the world of code than that! In the next chapter, you’re
going to learn about more types such as strings, which allow you to store text.
Add: +Subtract: -Multiply: *Divide: /Remainder: %
Add and assign: +=Subtractand assign: -=Multiplyand assign: *=Divideand assign: /=
raywenderlich.com48
Swift ApprenticeChapter 2: Expressions, Variables & ConstantsChallenges
Before moving on, here are some challenges to test your knowledge of variables
and constants. You can try the code in a playground to check your answers.
Declareaconstantexerciseswithvalue11andavariableexercisesSolvedwith
value 0. Increment this variable every time you solve an exercise (including this
one).
Giventhefollowingcode:
age =16print(age)
age =30print(age)
Declareagesothatitcompiles. Didyouusevarorlet?
3. Considerthefollowingcode:
let a:Int=46letb:Int=10
Workout what answer equals when you replace the final line of code above with
each of these options:
// 1
letanswer1:Int= (a *100) + b// 2letanswer2:Int= (a *100) + (b *100)// 3letanswer3:Int= (a *100) + (b /10)
4. Addparenthesestothefollowingcalculation.Theparenthesesshouldshowthe
order in which the operations are performed and should not alter the result of
the calculation.
5*3-4/2*2
5. DeclaretwoconstantsaandboftypeDoubleandassignbothavalue.Calculate
The average of a and band store the result in a constant named average.
6.Atemperatureexpressedin°Ccanbeconvertedto°Fbymultiplyingby1.8
then incrementing by 32. In this challenge, do the reverse: convert a
temperature from °F to °C. Declare a constant named Fahrenheit it of type Double and assign it a value. Calculate the corresponding temperature in °C and store
the result in a constant named celcius.
Suppose the squares on a chessboard are numbered left to right, top to bottom,
with 0 being the top-left square and 63 being the bottom-right square. Rows are
numbered top to bottom, 0 to?
7. Columns are numbered left to right, 0 to 7.
Declare a constant position and assign it a value between 0 and 63. Calculate
the corresponding row and column numbers and store the results in constants
named row and column.
DeclareconstantsnameddividendanddivisoroftypeDoubleandassignbotha
value. Calculate the quotient and remainder of an integer division of a dividend by the divisor and store the results in constants named quotient and remainder.
Calculate the remainder without using the operator %.
Acircleismadeupof2!radians,correspondingwith360degrees.Declare constant degrees
of type Double and assign it an initial value. Calculate the
corresponding angle in radians and store the result in a constant named radians.
Declare four constants namedx1,y1,x2andy2of type Double. These constants
represent the 2-dimensional coordinates of two points. Calculate the distance
between these two points and store the result in a constant named distance.
Increment variableexercisesSolveda final time. Use the print function to print
the percentage of exercises you managed to solve. The printed result should be
a number between 0 and 1.
http://www.itdecent.cn/
sqrt(2.0)// 1.414213562373095
max(5,10)// 10
min(-5, -10)// -10
variableNumber=1_000_000