Why does the Swift language guide suggest using Int “even when values are known to be non-negative”?

前端 未结 2 623
你的背包
你的背包 2020-12-24 04:49

This is a question about programming style in Swift, specifically Int vs UInt.

The Swift Programming Language Guide advises programmers to

2条回答
  •  星月不相逢
    2020-12-24 05:32

    It says in your question.. "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."

    This avoids issues such as assigning an Int to an UInt. Negative Int values assigned to UInts result in large values instead of the intended negative value. The binary representation of both doesn't differentiate one type from the other.

    Also, both are classes, one not descended from the other. Classes built receive Ints cannot receive UInts without overloading, meaning converting between the two would be a common task of UInts are being used when most of the framework receives Ints. Converting between the two can become a non-trival task as well.

    The two previous paragraphs speak to "interoperability" and "converting between different number types". Issues that are avoided if UInts aren't used.

提交回复
热议问题