Antoine Weber Antoine Weber - 9 days ago 6
Swift Question

How does an integer store a literal (eg var x = 0)

when i write

var x = 0


I know that
x
is an object that has properties and methods (created from Int Structure).

Where and how does x store the 0 ?

Is the 0 stored as a property of x ?

If yes, what would be the type of that property ?

If not, where is it stored ?

Answer

x is not an object, strictly speaking. "Object" is a name we give to instances of classes, not structs. x is an instance of the Int struct.

The Int structure wraps a Builtin integer type, and defines a bunch of methods you can call on it. That builtin integer literal type isn't accessible from Swift (nor is there a reason for it to be). Like all structures, instances of Int are stored on the runtime stack. They're not objects on the heap like Integer in Java, for example.

You can see the implementation details of (U)Int(8/16/32/64) here. This file uses the Generate Your Boilerplate (GYB) preprocessor created by the Swift team to generate .swift files from .swift.gyb template files. On line 221, you can see the property _value of type Builtin.${BuiltinName}. The GYB preprocessor expands this out so that Int has a _value of type Builtin.Int, Int64 has Built.Int64, etc.

Comments