Swift中Int与Int32/Int64能否安全使用==运算符比较?
== to compare Int with Int32/Int64 in Swift? Great question! Let’s break this down clearly, since it’s a common point of confusion even though Swift supports this natively.
Short Answer
Yes, you can safely use == to directly compare Int with Int32/Int64 in Swift. This isn’t an oversight—it’s an intentional language design feature, which is why you see no warnings or errors, and your Playground tests work as expected.
Why This Works
Swift’s standard library extends the Equatable protocol to support cross-type equality checks between all integer types (including Int, Int8, Int32, Int64, and their unsigned counterparts). The compiler handles the type coercion under the hood safely, as long as the values being compared fit within the bounds of both types.
Example code to confirm:
let standardInt: Int = 100 let int32Value: Int32 = 100 let int64Value: Int64 = 100 print(standardInt == int32Value) // Output: true print(standardInt == int64Value) // Output: true
Key Caveats to Keep It Safe
While direct comparison is supported, there are edge cases to watch for:
- Value range mismatches: If a value exceeds the maximum/minimum representable value of the other type, you’ll run into issues. For example, on a 32-bit system,
Intis 32 bits—comparing anInt64value of2_147_483_648(which is larger than the 32-bitIntmax) would fail because theIntcan’t even store that value in the first place. Most of the time, the compiler will catch this at assignment time, not comparison time. - Readability vs. conciseness: Many online answers suggest explicit type conversion (e.g.,
Int(int32Value)) not because it’s required for comparison, but because it makes the code more explicit for future maintainers. If your codebase has a lot of cross-type integer handling, explicit conversions can avoid confusion.
Why Most Answers Focus on Conversion
The focus on type conversion in other answers usually stems from arithmetic operations (not equality checks)—you can’t add an Int and Int32 directly, for example. For equality, though, Swift’s built-in support removes the need for conversion.
内容的提问来源于stack exchange,提问作者nuynait

