Swift – struct

A structure is generally used to define a light weight data object with small number of properties. A structure can contain properties of different datatypes.

struct keyword is used to define a structure in Swift programming language.

Syntax – struct in Swift

Following is the syntax of swift structure.

struct structureName {
     // structure_body
 }

where

structureName is the name by which we shall reference this structure.

sturcture_body can contain constructs, properties and methods.

Example 1 – Swift Structure

Following is a simple example where the structure car contains properties like brand, name and seating capacity.

main.swift

struct car {
   var brand: String
   var name: String
   var capacity: Int
   
   init(brand: String, name: String, capacity: Int) {
      self.brand = brand
      self.name = name
      self.capacity = capacity
   }
}

let car1 = car(brand: "Hyundai", name: "Creta", capacity: 5)

print("Car details\n-----------")
print("Brand is \(car1.brand)")
print("Name is \(car1.name)")
print("Seating capacity is \(car1.capacity)")

Output

Car details
-----------
Brand is Hyundai
Name is Creta
Seating capacity is 5

Example 2 – Initialize some properties of the structure with default values

You can initialize some properties to default values in a structure.

main.swift

struct car {
   var brand: String
   var name: String
   var capacity = 5
   
   init(brand: String, name: String) {
      self.brand = brand
      self.name = name
   }
}

let car1 = car(brand: "Hyundai", name: "Creta")

print("Car details\n-----------")
print("Brand is \(car1.brand)")
print("Name is \(car1.name)")
print("Seating capacity is \(car1.capacity)")

Output

Car details
-----------
Brand is Hyundai
Name is Creta
Seating capacity is 5

Example 3 – Swift Structure with Multiple init methods

This is kind of overloading methods. We can have multiple init methods with different sets of properties being initialized. But, you have to ensure that all the properties of the structure are being initialized.

main.swift

struct car {
   var brand: String
   var name: String
   var capacity: Int
   
   init(brand: String, name: String) {
      self.brand = brand
      self.name = name
      self.capacity = 5
   }
   
   init(brand: String, name: String, capacity: Int) {
      self.brand = brand
      self.name = name
      self.capacity = capacity
   }
}

let car1 = car(brand: "Hyundai", name: "Creta")
print("Car details\n-----------")
print("Brand is \(car1.brand)")
print("Name is \(car1.name)")
print("Seating capacity is \(car1.capacity)")

let car2 = car(brand: "Toyota", name: "Innova", capacity: 7)
print("\nCar details\n-----------")
print("Brand is \(car2.brand)")
print("Name is \(car2.name)")
print("Seating capacity is \(car2.capacity)")

Output

Car details
-----------
Brand is Hyundai
Name is Creta
Seating capacity is 5

Car details
-----------
Brand is Toyota
Name is Innova
Seating capacity is 7