How to get the size of a variable in memory in Swift

Overview

Whenever we create a variable, it uses memory. The size of the variable is dependent on the type of data. And of course, we have different data types in Swift:

  • Int
  • Float
  • Double
  • Bool
  • String
  • Character

We can get the size of a variable using the MemoryLayout.size(ofValue:) method.

Syntax

MemoryLayout.size(ofValue: variable)
Get the size of a variable in Swift

Parameters

variable: This is the variable and we must determine its size.

Return value

The value returned is an integer value representing the size of a variable in memory.

Example

import Swift
// create some variables
var var1:Bool = false;
var var2:String = "Hello";
var var3:Character = "A";
var var4:Int = 10;
var var5:Float = 15.5;
// print the sizes of the variables
print(MemoryLayout.size(ofValue: var1));
print(MemoryLayout.size(ofValue: var2));
print(MemoryLayout.size(ofValue: var3));
print(MemoryLayout.size(ofValue: var4));
print(MemoryLayout.size(ofValue: var5));

Explanation

In the code above:

  • Lines 4–8: We create different variables and initialize them.
  • Lines 11–15: We print the size of each variable using the MemoryLayout.size(ofValue:) method.

Free Resources