为什么在Swift中UInt64 max等于-1?

时间:2023-01-23 19:07:57

Using Swift, wether in terminal or playground, when I enter the following on a new line:

当我在新线路上输入以下内容时,使用Swift,在终端或游乐场中使用:

UInt64.max

I get a result value of -1.

我得到的结果值为-1。

Is this a bug?

这是一个错误吗?


Edit: Examples

$ xcrun swift
Welcome to Swift!  Type :help for assistance.
  1> UInt64.max / 2
$R1: UInt64 = 9223372036854775807
  2> UInt64.max / 2 + 1
$R2: UInt64 = -9223372036854775808
  3> UInt64.max
$R3: UInt64 = -1
  4> println(UInt64.max / 2)
9223372036854775807
  5> println(UInt64.max / 2 + 1)
9223372036854775808
  6> println(UInt64.max)
18446744073709551615

4 个解决方案

#1


6  

I think it is a bug of terminal and playground.

我认为这是终端和游乐场的错误。

But, the output of the println is correct(18446744073709551615) in both terminal and playground.

但是,println的输出在终端和游乐场都是正确的(18446744073709551615)。

#2


0  

Looks like the same bug I've run into with any unsigned type.

看起来像我遇到的任何无符号类型的错误。

echo "UInt8(255)" | xcrun swift

echo“UInt8(255)”| xcrun swift

will also print -1

也将打印-1

#3


-1  

It's because your processor is of 64 bit and UInt is 64 bit * 2. The type Int can't run this number, it's out of range.

这是因为你的处理器是64位,UInt是64位* 2.类型Int不能运行这个数字,它超出范围。

#4


-1  

This is still a bug, even with the REPL in Swift 2.2. See https://bugs.swift.org/browse/SR-1007 or https://bugs.swift.org/browse/SR-1138.

即使使用Swift 2.2中的REPL,这仍然是一个错误。请参阅https://bugs.swift.org/browse/SR-1007或https://bugs.swift.org/browse/SR-1138。

Fixed in Playgrounds with XCode 7.3 though.

虽然在使用XCode 7.3的Playgrounds中修复了。

#1


6  

I think it is a bug of terminal and playground.

我认为这是终端和游乐场的错误。

But, the output of the println is correct(18446744073709551615) in both terminal and playground.

但是,println的输出在终端和游乐场都是正确的(18446744073709551615)。

#2


0  

Looks like the same bug I've run into with any unsigned type.

看起来像我遇到的任何无符号类型的错误。

echo "UInt8(255)" | xcrun swift

echo“UInt8(255)”| xcrun swift

will also print -1

也将打印-1

#3


-1  

It's because your processor is of 64 bit and UInt is 64 bit * 2. The type Int can't run this number, it's out of range.

这是因为你的处理器是64位,UInt是64位* 2.类型Int不能运行这个数字,它超出范围。

#4


-1  

This is still a bug, even with the REPL in Swift 2.2. See https://bugs.swift.org/browse/SR-1007 or https://bugs.swift.org/browse/SR-1138.

即使使用Swift 2.2中的REPL,这仍然是一个错误。请参阅https://bugs.swift.org/browse/SR-1007或https://bugs.swift.org/browse/SR-1138。

Fixed in Playgrounds with XCode 7.3 though.

虽然在使用XCode 7.3的Playgrounds中修复了。