Swift Data Types

Interactive Online Courses: Elevate Skills & Succeed Enroll Now!

In Swift, once we declare a constant or a variable, we cannot change its type later. This is why it is a statically typed language. It determines how the data is stored and manipulated based on its type. It is important to understand data types to implement them efficiently. We’ll learn about different data types supported in Swift in this article with the help of relevant examples.

Some of the built-in data types in Swift are as follows:

Data TypeDescriptionExample
IntInteger Number20, -40
Float32-bit Floating Point Number35.6
Double64-bit Floating Point Number3.141592653589793 
BoolEither true/falsetrue, false
Character16-bit Unicode Character“D”, “f”
StringSequence of Characters“DataFlair”

We’ll learn about different data types supported in Swift in this article with the help of relevant examples.

Data Types Sizes

The size of a data type determines the size of data a variable or a constant can store. We measure the size in bits. It can store a maximum value of 2 bits.

For example, there is a data type of 2-bit size. The maximum number of values it can store is 22= 4.

ValueBinary Representation
000
101
210
311

A data type of n-bit size can store a maximum of 2n bits.

Basic Data Types

A basic data type is also known as a primitive data type. It refers to a building block for representing values. These are directly supported by the language.

Integers

Integers represent whole numbers without any decimal points. We have two main types of integers in Swift: Int and UInt.

Int can have negative and positive values.

UInt is an unsigned integer; It holds non-negative values only.

var temperature: Int = -40 	// holds positive and negative integers.
var age: UInt = 22		// holds only non-negative integers.

The below table represents the integer variable type, the amount of memory it consumes, and its range.

TypeBit width (in bytes)Range
Int81[-128, 127]
Int324[-2147483648, 2147483647]
Int648[-9223372036854775808,  9223372036854775807]
UInt81[0, 255]
UInt324[0, 4294967296]
UInt648[0, 18446744073709551616]

Floating Point Numbers

Floating point numbers represent numbers with fractional components. These are of two types: Float and Double.

Float is a 32-bit floating point number. Its precision can be 6 decimal digits.

Double is a 64-bit floating point number. Its precision can be at least 15 decimal digits.

We use Double when precision is crucial. We use Float when memory efficiency is essential.

var pi: Double = 3.141592653589793 
var temperature: Float = 25.8

The below table represents the type, the amount of memory it consumes, and its range.

TypeBit width (in bytes)Range
Float4[1.2E-38, 3.4E+38] (~6 digits)
Double8[2.3E-308, 1.7E+308] (~15 digits)

Booleans

Booleans represent binary states in our programs. It can contain two values: true and false.

var isWeekend: Bool = false
var isFun: Bool = true

Character

Characters are individual Unicode values, which are numerical representations of individual characters. It handles single characters in Swift. It represents individual textual elements. The individual characters might be letters, digits, punctuation marks, symbols, or whitespace.

var initialCharacter: Character = "D"

String

A sequence of characters is a string. It stores information or data in textual format. Swift provides a powerful and flexible String type. It can support Unicode and various string manipulation functions.

var example: String = "DataFlair"

Collection Data Types

Collection data types store multiple elements of the same or different data types together. It stores these groups of values in a well-structured way.

Arrays

Arrays are ordered collections of elements. It stores elements of the same data type. In Swift, the index of arrays starts from 0, so they are zero-indexed.

var arrayExample: [String] = ["DataFlair", "Swift", "Data Types", "Array"]

Dictionaries

Dictionaries are unordered collections. It contains a key linked with a value. It has key-value pairs in it. In a dictionary, each key is unique. The values in it can be of any data type.

var dictionaryExample: [String: Int] = ["DataFlair": 1, "Swift": 5]

Sets

Sets are unordered collections. Each element in it is unique. These are useful when we want to ensure that each appears only once.

var setExample: Set<String> = ["DataFlair", "Swift", "Data Types", "Set"]

Advanced-Data Types

Advanced Data Types are composed of multiple basic or collection data types. They are complex data structures.

Tuples

A tuple is a collection of two or more values clubbed together into a single compound value. They can be of different data types. Tuples can be useful when we have to combine and pass around parts of data as a single unit.

var tupleExample: (String, String) = ("DataFlair", "Tuples")

Optionals

Optionals are a special data type in Swift. They are used when a variable or constant might have a value or might be nil. We define an optional by appending a question mark (?) in the type declaration.

var optionalExample: String? = "DataFlair"

Enums

Enums are also known as enumerations. It is a custom data type. It makes a group of related values as a single data type. It provides type safety for various cases or states.

enum Season{
    case summer
    case winter
    case spring
    case autumn
}
let season: Season = .spring
switch season{
case .summer:
    print("It's summer")
case .winter:
    print("It's winter")
case .spring:
    print("It's spring")
case .autumn:
    print("It's autumn")
}

Output:

It’s spring

Type Inference

Swift has one powerful capability, which is type inference. It means the compiler can automatically deduce the data type of a variable based on the context.

var intExample = 2023 		      // infers it as an Int
var stringExample = "DataFlair" 	// infers it as a String

Conclusion

To conclude, data types in Swift are essential. They determine how data is stored, manipulated, and organized. Basic data types handle simple values. Collection data types manage groups of data. Advanced data types model complex structures and behaviors. Swift’s type inference simplifies variable declarations.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *