Swift - Nested Types



The nested type is a very powerful tool in Swift programming. Using nested type we can able to easily nest enumerations, classes and structures into other enumerations, classes and structures. Using nested type we can nest an enumeration or class into a structure or vice versa. So we can say that by using nested types we can create complex custom types.

Nested types are commonly used to create well-organized and hierarchical programs. They are also used to encapsulate code so that we can easily understand it. They also reduce namespace conflicts.

Creating Nested Types

We can create nested types by defining a structure into another structure or a class into another class just like the nested functions. We can create multiple structures, classes and enumerations in another structure, class and enumerations.

Syntax

Following is the syntax of the nested types −

Struct Name{
   Struct name{
      // body
   }
}

Using this syntax we can nest classes and enumerations.

Example

Suppose we are creating a structure of a car in which we have multiple types of features like colour and sunroof. So using nested type we can define each type of specifications.

struct Car{
   struct Color{
      var single: String
      var double: String
      var customize: String
   }
   struct Sunroof{
      var half: String
      var full: String
   }
}

Creating Instance of Nested Types

We can create instances of nested types using the dot operator. So simply prefix the name of the outer type followed by the dot operator and then specify the nested type name. Every nested type has its instance.

Syntax

Following is the syntax for creating instances of nested types −

let name = outerTypeName.nestedTypeName(value: type)

Or,

var name = OuterTypeName(label1:Value, lable2: 
OuterTypeName.NestedTypeName(label: Value, lable2: Value))

Example

Let's create the instance of the above-nested types −

let instance1 = Car.Color(single: "Yellow", double: "Green Black", customize: "Blue")
let instance2 = Car.Sunroof(half: "yes", full: "No")

Or,

var myCar = Car(name:"Breeza", color: Car.Color(
single: "Blue", double: "No", customize: "White"), 
sunroof:Car.Sunroof(half: "Yes", full: "No"))

The complete example is −

import Foundation

// Outer sturtcure
struct Car{

   // Nested structure 1
   struct Color{
      var single: String
      var double: String
      var customize: String
   }
   // Nested structure 1
   struct Sunroof{
      var half: String
      var full: String
   }
    
   // Properties
   var name: String
   var color: Color
   var sunroof:Sunroof
}

// Creating instance of Car structure
var myCar = Car(name:"Breeza", color: Car.Color(single: "Blue", double: "No", customize: "White"), sunroof:Car.Sunroof(half: "Yes", full: "No"))

// Displaying Data
print("Car name:", myCar.name)
print("Car Color:", myCar.color.single)
print("Have half Sunroof:", myCar.sunroof.half)

Output

It will produce the following output −

Car name: Breeza
Car Color: Blue
Have half Sunroof: Yes

Enumerations within Structure

Using nested types it is not necessary that you can only nest a structure into another structure. We can also nest an enumeration inside another structure or vice versa.

Example

Swift program to nest enumeration inside a structure.

import Foundation

// Outer structure
struct Tutorialspoint {

   // Nested enum
   enum Department {
      case HR
      case Development
      case Designing
      case ContentWriting
   }
    
   // Properties
   var name: String
   var location: String
   var department: Department
    
   init(name: String, location: String, department: Department) {
      self.name = name
      self.location = location
      self.department = department
   }
    
   // Method
   func employeeDetail() {
      print("Name: \(name)")
      print("Location: \(location)")
      print("Department: \(department)")
   }
}

let report = Tutorialspoint(name: "Mona", location: "Hyderabad", department: .Designing)
report.employeeDetail()

Output

It will produce the following output −

Name: Mona	
Location: Hyderabad
Department: Designing

Structure within Class

Using nested types we are allowed to nest a structure within a class or a class within a structure without getting any error.

Example

Swift program to nest structure inside another class.

import Foundation

// Outer class
class XYZCollege {

   // Nested structure
   struct StudentDetail {
      var name: String
      var age: Int
      var subject: String
      var year: Int
   }
    
   // Properties
   var department: String
   var details: [StudentDetail]
    
   init(department: String) {
      self.department = department
      self.details = []
   }
    
   // Method 1
   func newStudents(student: StudentDetail) {
      details.append(student)
   }
    
   // Method 2
   func studentsData() {
      print("department name: \(department):")
      for s in details {
         print("name: \(s.name), age: \(s.age), subject: \(s.subject), year: \(s.year)")
      }
   }
}

// Creating instances
let s = XYZCollege(department: "Science")
let stud1Detail = XYZCollege.StudentDetail(name: "Mona", age: 19, subject: "Maths", year: 1)
let stud2Detail = XYZCollege.StudentDetail(name: "Pihu", age: 18, subject: "Chemistry", year: 1)
let stud3Detail = XYZCollege.StudentDetail(name: "Suman", age: 19, subject: "Maths", year: 1)

// Accessing the methods
s.newStudents(student: stud1Detail)
s.newStudents(student: stud2Detail)
s.newStudents(student: stud3Detail)

s.studentsData()

Output

It will produce the following output −

department name: Science:
name: Mona, age: 19, subject: Maths, year: 1
name: Pihu, age: 18, subject: Chemistry, year: 1
name: Suman, age: 19, subject: Maths, year: 1
Advertisements