Swift, is rich in data types. The storage representation and machine instructions differ from machine to machine. Swift provides various types of data-types that allow programmers to select the appropriate type for the variable to set its value.
What are Data types?
Data type of any programming language is a collection of data with variables having fixed meanings as well as distinctiveness. Various types of data types are provided by Swift language. These are:
Integers are whole numbers with no fractional component, such as 42 and -23. Integers are either signed (positive, zero, or negative) or unsigned (positive or zero). Swift provides signed and unsigned integers in 8, 16, 32, and 64 bit forms. These integers follow a naming convention similar to C, in that an 8-bit unsigned integer is of type UInt8, and a 32-bit signed integer is of type Int32. Like all types in Swift, these integer types have capitalized names. Programmers can access the minimum and maximum values of each integer type with its min and max properties:
- Let minValue = UInt8.min // minValue is equal to 0, and is of type UInt8
- Let maxValue = UInt8.max // maxValue is equal to 255, and is of type UInt8
This is used to represent a 32-bit floating-point number and numbers with smaller decimal points. For example, 3.14159, 0.6, and -273.158. Swift offers programmers with two floating point number types. These are:
- Double: This represents a single bit floating point number. Programmers need to use it when floating point values are very large or particularly precise.
- Float: This is used to represent a 32 bit floating point number. Programmers need to use it when floating point values do not require 64 bi precision.
It is to be noted that Double has a precision of at least 15 decimal digits, whereas the precision of Float can be as little as 6 decimal digits. The appropriate floating-point type to use depends on the nature and range of values you need to work within your code.
This represents a Boolean value which is either true or false.
This is a single-character string literal. For example, “G”
This is an ordered collection of characters as a single unit. For example, “Hello”.
Swift provides another facility where programmers can represent a variable that can hold either a value or no value.
- For a 32-bit platform, Int is the same size as Int32.
- For a 64-bit platform, Int is the same size as Int64.
- For a 32-bit platform, UInt is the same size as UInt32.
- For a 64-bit platform, UInt is the same size as UInt64.
Here is a table showing the maximum and minimum value which can be stored in such type of variables:
|Int8||1byte||-127 to 127|
|UInt8||1byte||0 to 255|
|Int32||4bytes||-2147483648 to 2147483647|
|UInt32||4bytes||0 to 4294967295|
|Int64||8bytes||-9223372036854775808 to 9223372036854775807|
|UInt64||8bytes||0 to 18446744073709551615|
|Float||4bytes||1.2E-38 to 3.4E+38 (~6 digits)|
|Double||8bytes||2.3E-308 to 1.7E+308 (~15 digits)|