Why is UInt64 max equal -1 in Swift?

百般思念 提交于 2019-12-19 20:49:14

问题


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

UInt64.max

I get a result value of -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

回答1:


I think it is a bug of terminal and playground.

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




回答2:


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

echo "UInt8(255)" | xcrun swift

will also print -1




回答3:


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.




回答4:


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.

Fixed in Playgrounds with XCode 7.3 though.



来源:https://stackoverflow.com/questions/24218918/why-is-uint64-max-equal-1-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!