Swift学习——Swift基础详解(三)

时间:2021-03-04 22:24:12

小葵花课堂继续开讲


Numeric Literals    数字文本

数字文本有以下几种写法:

A decimal number, with no prefix
A binary number, with a 0b prefix
An octal number, with a 0o prefix
A hexadecimal number, with a 0x prefix
十进制数,无前缀;二进制数,0b前缀;八进制数,0o前缀;十六进制数,0x前缀

论数字17的N种表现形式:

let decimalInteger = 17
let binaryInteger = 0b10001       // 17 in binary notation
let octalInteger = 0o21           // 17 in octal notation
let hexadecimalInteger = 0x11     // 17 in hexadecimal notation
也可以用十六进制和十进制表示浮点数,科学计数法,十进制用e表示10的指数,十六进制用p表示2的指数
For decimal numbers with an exponent of exp, the base number is multiplied by 10exp:

1.25e2 means 1.25 × 102, or 125.0.
1.25e-2 means 1.25 × 10-2, or 0.0125.
For hexadecimal numbers with an exponent of exp, the base number is multiplied by 2exp:

0xFp2 means 15 × 22, or 60.0.
0xFp-2 means 15 × 2-2, or 3.75.
浮点数12.1875的几种表现形式:
let decimalDouble = 12.1875
let exponentDouble = 1.21875e1
let hexadecimalDouble = 0xC.3p0
数字文本可以使用其他的一些格式让数字变得更加易读,比如添加0或者下划线,不会影响数字的值(这个功能不错):

let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1


Numeric Type Conversion    数值类型转换

通常情况下就使用int,当有其他需要,比如性能或者内存需要的时候可以使用别的整型类型,这个时候使用明确大小的类型可以帮助你捕获异常的溢出



Integer Conversion    整型之间转换

每种整型存储的数值范围是不同的,In8存储的范围是(-128 ,127),UInt8存储的范围是(0 , 255),如果存储的数字超过范围,编译的时候会报错

let cannotBeNegative: UInt8 = -1
// UInt8 cannot store negative numbers, and so this will report an error
let tooBig: Int8 = Int8.max + 1
// Int8 cannot store a number larger than its maximum value,
// and so this will also report an error
其实就是整型的强制类型转换,比如下边例子中的UInt16和UInt8是不能直接相加的,需要把UInt8转换成UInt16类型:

let twoThousand: UInt16 = 2_000
let one: UInt8 = 1
let twoThousandAndOne = twoThousand + UInt16(one)



Integer and Floating-Point Conversion    整型和浮点型之间转换
整型和浮点型相加也要做出明确的类型转换,不转换会报错(泥煤,for security?):

let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = Double(three) + pointOneFourOneFiveNine
// pi equals 3.14159, and is inferred to be of type Double
浮点型也可转换成整型,小数位被舍去:

let integerPi = Int(pi)
// integerPi equals 3, and is inferred to be of type Int
额,本章后面原文写了个Note,看了半天才明白怎么个情况,原文如下:

The rules for combining numeric constants and variables are different from the rules for numeric literals. 
The literal value 3 can be added directly to the literal value 0.14159, because number literals do not have 
an explicit type in and of themselves. Their type is inferred only at the point that they are evaluated by the compiler.
其实翻译过来的意思就是,在等号的右边,你写的数值是不需要类型转换的,比如,你可以这么写:

let iamDouble = 3 + 0.14159
这个时候,3不需要进行类型转换,因为编译器之前不知道他的类型(只是猜测是整型),如果等号右边是整型常量或者变量的话,就需要转换成Double类型