Objective-C int 作为 Int32 桥接到 Swift

Objective-C int is bridged as Int32 to Swift

如果我是正确的,Objective-C 的 int 类型长度取决于平台字长(即在 64 位环境中 运行 时它是 64 位,而在 32 -bit when 运行 in a 32-bit environment).

但是,当将 Objective-C 接口桥接到 Swift 时,此类型被桥接为 Int32,它明确定义了 32 位的大小。

这是一个错误,还是Objective-C中的int总是占32位?如果这不是错误,为什么它被桥接为 Int32?

Objective-C 界面示例

-(int)numberOfItems;

桥接到:

func numberOfItems -> Int32

当我将方法签名更改为使用 NSInteger 时,它会正确桥接:

-(NSInteger)numberOfItems;
func numberOfItems -> Int

如果我将 Objective-C 中的 int 更改为 NSInteger 是否有任何危险,或者这些类型在 Objective-C 中的行为方式完全相同?

Objective C的int(或者更准确地说,Cint)应该是at least 16 bits in size, so storing it in 32 bits is not invalid. Probably in Apple's implementation it is always 32 bit for int.

If I'm correct, Objective-C's int type length depends on the platform word length (i.e. it's 64 bit when running in a 64-bit environment and 32-bit when running in a 32-bit environment).

那将是 NSInteger,而不是 int。您可能会混淆它们,因为在 SwiftIntObjective CNSInteger 的等效类型。

您甚至可以在文档中看到它:

typealias NSInteger = Int

Swift 不是从 generic (Objective-)C 桥接而是从 Apple (Objective-)C。在标准 C 中,int 的大小只有最小界限,没有精确大小。然而,Apple(和 GNU)编译器遵循数据类型大小的特定模型,来自 Apple 的 64-Bit Transition Guide:

OS X uses two data models: ILP32 (in which integers, long integers, and pointers are 32-bit quantities) and LP64 (in which integers are 32-bit quantities, and long integers and pointers are 64-bit quantities). Other types are equivalent to their 32-bit counterparts (except for size_t and a few others that are defined based on the size of long integers or pointers).

因此在 ILP32(用于 32 位应用程序)和 LP64(64 位应用程序)中,int 的大小都是 32 位。 Swift 中的等效整数类型是 Int32.

关于 NSInteger 相同的参考状态:

In addition to these changes to the base data types, various layers of OS X have other data types that change size or underlying type in a 64-bit environment. The most notable of these changes is that NSInteger and NSUInteger (Cocoa data types) are 64-bit in a 64-bit environment and 32-bit in a 32-bit environment.

Swift 等价于 Int.