Swift - Data Types


Data types are an important part of any programming language; they specify the type of data to be stored in a variable and how many bytes are required to store that data. Like other programming languages, Swift also provides a set of data types that define the type and size of data to be stored in a variable.

Subsequently, when desiring to store data in the variable we can enter data of any type such as string, character, wide character, integer, floating point, Boolean, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory.

Built-in Data Types

Swift offers the programmer a rich assortment of built-in data types, also known as primitive data types. They represent the basic values and are directly supported by the Swift language. Swift provides seven types of built-in data types and they are −

Datatype Name Description
Int or Uint This is used for whole numbers. More specifically, you can use Int32, Int64 to define 32 or 64-bit signed integers, whereas UInt32 or UInt64 to define 32 or 64-bit unsigned integer variables. For example, 42 and -23.
Float This is used to represent a 32-bit floating-point number and numbers with smaller decimal points. For example, 3.14159, 0.1, and -273.158.
Double This is used to represent a 64-bit floating-point number and is used when floating-point values must be very large. For example, 3.14159, 0.1, and -273.158.
Bool This represents a Boolean value which is either true or false.
String This is an ordered collection of characters. For example, "Hello, World!"
Character This is a single-character string literal. For example, "C"
Optional This represents a variable that can hold either a value or no value.

The following table shows the data type, how much memory it takes to store the value in memory, and what is the maximum and minimum values that can be stored in such types of variables.

Type Typical Bit Width Typical Range
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)

User-Defined Data Types

User-defined data types allow us to create customized data types according to their requirements. They provide more flexibility and abstraction. Following are some user-defined data types supported by Swift −

Type Name Description
Structures(struct) They are value types; means they can have copied when passed around in the program. They are good for representing simple data structure.
Class They are reference types; means they are passed as a reference. They are good for complex data models and objects.
Enumerations(Enum) They are used to define a group of related values. They are good at representing finite set.
Protocols They define a blueprint for methods and properties that is good for a particular task or piece of functionality.

Defining Variables with Specific Types

To store a specific type of value, you need to declare a variable with the appropriate data type. For example, if you want to store an integer, the variable should be declared using the Int data type.

Syntax

Following is the syntax to declare variable with the built-in data type −

var name : dataType = Value

Example

Here is the declaration of some of the variables with different data types −

var index : Int = 10
var str   : String = "Learn Swift!"
var char  : Character = "S"
var num   : Float = 23.45
var nums  : Double = 32.233434
var value : Bool = true

Defining User-defined Data Types

User-defined data types are defined with the help of built-in types where you can group multiple values of different or similar types under a single name. Swift provides three main types of user-defined data types:

  • Structures (struct)
  • Classes (class)
  • Enumerations (enum)

Now we will see how to define user-defined data types:

Syntax

Following is the syntax of a user-defined data type using a struct

struct Student {
   var name: String
   var age: Int
}

var myData = Student(name: "Mona", age: 23)

Structure Example

Swift program demonstrating how to define and use a structure −

import Foundation

// Structure
struct Employee {
   var name: String
   var age: Int
}

// Creating and printing structure instance
let emp = Employee(name: "Seema", age: 23)
print("Employee Name: \\(emp.name)")
print("Employee Age: \\(emp.age)")

The output of the above example is:

Employee Name: Seema
Employee Age: 23

Class Example

Swift program demonstrating how to define and use a class −

import Foundation

// Class
class Student {
   var name: String
   var age: Int

   init(name: String, age: Int) {
      self.name = name
      self.age = age
   }
}

// Creating and printing class instance
let student = Student(name: "Alice", age: 25)
print("Student Name: \\(student.name)")
print("Student Age: \\(student.age)")

The output of the above example is:

Student Name: Alice
Student Age: 25

Enumeration Example

Swift program demonstrating how to define and use an enumeration −

import Foundation

// Enumeration
enum Rectangle {
   case length, width, breadth
}

// Creating and printing enum value
let side: Rectangle = .length
print("Selected side: \\(side)")

The output of the above example is:

Selected side: length

Type Safety

Swift is a type-safe language. It means that if a variable of your program expects a String, you can't pass int in it by mistake because Swift performs type-checks while compiling your code and displays an error message if it finds any type mismatch.

However, this does not imply that you have to specify the type of every variable or constant. Swift applies type inference which automatically determines the type of the variable or constant if it is not specified explicitly.

Example

Swift program to demonstrate type Safety.

var varA = 42

// Here compiler will show an error message because varA 
// variable can only store integer type value
varA = "This is hello"

print(varA)

The output of the above example is:

main.swift:5:8: error: cannot assign value of type 'String' to type 'Int'
varA = "This is hello"

Type Inference

Type inference is a special feature of Swift language; it allows the compiler to automatically deduce the type of the given expression at the time of compilation. It means you do not need to explicitly define the type of the variable at the time of declaration and still Swift will provide string type safety.

It is useful when you declare a constant or variable with its initial value.

Example

Swift program to demonstrate type inference.

import Foundation

// varA is inferred to be of type Int
var varA = 42
print("Type of varA variable is:", type(of:varA))

// varB is inferred to be of type Double
var varB = 3.14159
print("Type of varB variable is:", type(of:varB))

// varC is also inferred to be of type String
var varC = "TutorialsPoint"
print("Type of varC variable is:", type(of:varC))

The output of the above example is:

Type of varA variable is: Int
Type of varB variable is: Double
Type of varC variable is: String