注释:
注释始终特殊的代码,他并不会被编译器解释为CPU可以理解的二进制指令,而是代码作者解释给其他作者或者浏览者的人类的语言。是对自己代码功能的一种解释。
单行注释: "'//" 比如:// This is a comment. It is not executed.
多行注释一: 多个"//"
// This is also a comment.
// Over multiple lines.
多行注释二: 以 /*开头, 以*/结尾
/* This is also a comment.
Over many...
many...
many lines. */
打印输出:
print("Hello, Swift Apprentice reader!")
在创建的工程中输入以上代码,就会将内容打印到控制台。
数学运算:
基本的运算加减乘除的表示方式如下:
这里需要注意的是,Swift语言与其他编程语言的语法差别,空格居然是个敏感词,在操作符的前后,要么都有空格,要么都没有,否则就会报错:
2+6// OK
2+6// OK
2+6// ERROR
2+6// ERROR
这大概是这一小节里面唯一值得说明一下的内容了。
小数:
小数需要注意的就是参与运算的数字的类型,遵循的原则就是:运算结果的类型与参与运算的数字中精度最高的数字的类型相同,这个再英文版中描述的不是很清楚。我把例子列出来。
27 / 7 = 3 结果是3,因为参与运算的两个数字都是整数,所以结果也是整数,不是4舍5入,只是取结果中的整数部分.
以下三种情况的结果都是 3.857142857142857。因为参与运算的双方至少有一个数是小数。所以结果按照小数来处理,当然这个小数还涉及到计算机能表达的精度问题,不同类型的计算机能表的小数的精度也不一样。 所谓的精度,比如三分之一这个数字在计算机中的表示就不可能小数点之后有无穷多个3,只能是在表达能力范围以内尽可能的接近真实值。这个接近程度指的就是精度。
27/7.0
27.0/7
27.0/7.0
取模:
这个操作指的就是除法中的余数,小学问题不解释,取模的运算符号为:%。这里需要注意的是,原文并没有提及参与取模的必须是整数, 否则就会报错。这是个又去的问题,如果你是名java程序员,你可以试验一下,对两个float类型的数取模,编译器会怎么处理,运算结果又是什么。在playground中运行会报错:
error: '%' is unavailable: Use truncatingRemainder instead 27.0 % 7
位移:
位移指的是将数字的二进制形式进行比特位的转换,分为左移和右移。其实这个话题不适合做这么简单的介绍,因为移动还和计算机的长度有关系,如果移动太多超出计算机的表达长度,比如之前的提到的32bit和64bit的cpu。他们只能一次表示一个32(64)个bit位的数字,如果把15这个数字左移动32位,你看一下结果和预想的完全不一样。在这里不纠结这个问题,在正常情况下,左移就是乘以2,右移就是除以2。位移的好处就是对于cpu来说,这个操作需要消耗的时间少一些。
记得有位大神卡马克,编写的3D游戏引擎。里面有很多用位移来取代复杂数学函数的代码,当年学习很久,有些到现在还没整明白,据说有位大学教授专门写论文,论证了里面一个数学常数对于计算机进行数学函数运算的优势,数学函数运算包含正弦,余弦,开平方等操作。
预算符号的优先级:
这也是小学问题,不纠结:350/5+2 = 72 而 350/ (5+2) = 50
数学函数:
swift 提供了很多数学运算的函数,这些函数有些不是操作系统本来就有的。其中包含一些三角函数,开平方运算和取大小值:
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
为数据命名:
从这开始才算是这是开始Swift预言的学习,
为常量命名: let number:Int=10 ,定义一个Int类型的常数number,初始化值为10.这个number的值一旦出事化,以后就无法再赋值,如果执行 number = 12 这类操作,会直接报错,因为这是常量,常量的意思就是一旦初始化就不再改变的量。
变量:var variableNumber:Int=42 定义一个Int类型,值为42的变量 variableNumber,你可以再随后的操作中修改这个变量的值。 例如 再次赋值 variableNumber = 12;下面这个操作很有意思:variableNumber=1_000_000 此时变量的值为1000000,这应该是方便土豪去数零方便,这个语法在别的语言应该少见吧。
命名规则:其实每个人都有自己的命名爱好,只是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等价运算
小结:本节讲解的是基础的数字命名及运算,需要注意的是,如果你是从别的语言转学Swift,本节中需要注意的是2点:
1.操作符前后要么有空格,要么没有空格
2.变量名可以是Unicode并且取模的运算只能交给Int类型数据参与,其他类型数据取模操作会出错。
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 “likes”
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.jianshu.com/
sqrt(2.0)// 1.414213562373095
max(5,10)// 10
min(-5, -10)// -10
variableNumber=1_000_000
网友评论