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.
MemoryLayout.size(ofValue: variable)
variable
: This is the variable and we must determine its size.
The value returned is an integer value representing the size of a variable in memory.
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));
In the code above:
MemoryLayout.size(ofValue:)
method.RELATED TAGS
CONTRIBUTOR
View all Courses