<分区>
在软件开发中,利用编译器错误通常是个好主意。让编译器通过检查你的代码为你工作是有道理的。在强类型语言中,如果一个变量只有两个有效值,您可以将其设为 bool 值或为其定义一个枚举。 Swift 通过引入 Optional
类型进一步加强了这一点。
在我看来,这同样适用于无符号整数:如果您知道负值是不可能的,请以强制执行的方式进行编程。 我说的是高级 API;而不是负值通常用作隐蔽错误信号机制的低级 API。
还有苹果 suggests避免使用无符号整数:
Use
UInt
only when you specifically need an unsigned integer type with the same size as the platform’s native word size. If this is not the case,Int
is preferred, even when the values to be stored are known to be non-negative. [...]
这是一个例子:Swift 的 Array.count
返回一个 Int
。一个人怎么可能有负数量的元素?!
为什么?!
Apple 声明:
A consistent use of
Int
for integer values aids code interoperability, avoids the need to convert between different number types, and matches integer type inference, as described in Type Safety and Type Inference.
但我不买账!使用 Int
不会比 UInt
更有助于“互操作性”,因为 Int
可以解析为 Int32
或 Int64
(分别用于 32 位和 64 位平台)。
如果您完全关心稳健性,在没有逻辑意义的地方使用有符号整数本质上会强制进行额外检查(如果值为负怎么办?)
我看不出在有符号和无符号之间转换是微不足道的。这难道不是简单地指示编译器将机器代码解析为使用有符号或无符号字节码吗?!