Swift 提供了两大类数字:整数和浮点数。
你可以在数字字面量中插入下划线来提高可读性:1_000_000 和 1000000 完全相同。
浮点字面量可以用十进制或指数记法书写。
let speed: Int = 42 // Explicit Int
let pi: Double = 3.14 // Explicit Double
let giga: Double = 1_000_000_000 // Double with readability underscores
let plancksConstant: Double = 6.62607015e-34 // Double in scientific notation
Swift 提供了标准的算术运算符用于数值计算:
| 运算符 | 说明 | 示例 |
|---|---|---|
+ |
加法 |
4 + 6 的结果是 10
|
- |
减法 |
15 - 10 的结果是 5
|
* |
乘法 |
2 * 3 的结果是 6
|
Swift 是类型安全的,不允许在算术运算中混用不同的数字类型。
你不能直接把 Int 和 Double 相加或相乘;必须先转换其中一个类型,使两者一致。
/运算符执行除法。
当两个操作数都是整数时,整数除法会截断小数部分:
5.0 / 2.0 // 2.5 (Double division)
5 / 2 // 2 (integer division truncates the remainder)
非零浮点数除以零会得到inf或-inf。
0.0除以0.0会产生nan(Not a Number)。
相比之下,整数除以零会导致编译时或运行时错误:
print(5.0 / 0.0) // Prints inf
print(-5.0 / 0.0) // Prints -inf
print(0.0 / 0.0) // Prints nan
// The following line will not compile:
// print(5 / 0) // Error: Division by zero
求余运算符(%)计算两个整数相除后剩下的余数:
5 % 2 // 1
-5 % 2 // -1
// Dividing by zero produces an error:
// 5 % 0 // Error: Division by zero
在 Swift 中,% 是真正的求余运算符,而不是求模运算符。
结果始终取第一个操作数(被除数)的符号,与第二个操作数的符号无关:
5 % -2 // 1
-5 % 2 // -1
你可以使用rounded()方法对浮点数取整。
默认情况下,rounded()会取最接近的整数。
你也可以指定具体的舍入规则,例如.up或.down:
let x = 3.14
let y = x.rounded() // 3.0
let w = x.rounded(.down) // 3.0
let z = x.rounded(.up) // 4.0
当你不加类型标注声明数字常量或变量时,Swift 会推断它的类型:
Int。Double。let x = 42 // Inferred as Int
let y = 42.0 // Inferred as Double
let z: Double = 42 // Explicitly typed as Double
要在不同类型的值之间进行运算,可以用Double(_:)或Int(_:)这样的类型初始化器转换其中一个值:
let integerCount = 42
let floatingCount = Double(integerCount)
print(floatingCount) // Prints 42.0
let pi = 3.14
let integerPi = Int(pi)
print(integerPi) // Prints 3 (fractional part is truncated)