Objective-C int is bridged as Int32 to Swift

2.8k views Asked by At

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).

However, when bridging an Objective-C interface to Swift, this type is bridged as Int32 which explicitly defines the size of 32 bits.

Is this an error, or int in Objective-C always occupies 32 bit? If it's not an error, why it gets bridged as Int32?

Example of the Objective-C interface

-(int)numberOfItems;

Which gets bridged into:

func numberOfItems -> Int32

When I change the method signature to use NSInteger, it get's bridged correctly:

-(NSInteger)numberOfItems;
func numberOfItems -> Int

Is there any danger if I change int in Objective-C to NSInteger, or these types behave in exactly the same manner in Objective-C?

2

There are 2 answers

3
user28434'mstep On BEST ANSWER

Objective C's int (or to be correct, C's int) should be 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).

That would be NSInteger, not int. You may be confusing them because in Swift's Int is equivalent type for Objective C's NSInteger.

You can even see it in the docs:

typealias NSInteger = Int
0
CRD On

Swift is not bridging from generic (Objective-)C but from Apple (Objective-)C. In Standard C the size of int has only a minimum bound and not an exact size. However the Apple (& GNU) compilers follow specific models for data type sizes, from Apple's 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).

So in both ILP32 (used for 32-bit apps) and LP64 (64-bit apps) the size of int is 32-bits. The equivalent integer type in Swift is Int32.

Regarding NSInteger the same reference states:

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's equivalent is Int.