Swift Nested Types

In swift, Nested types are the types that we can nest other types in our type definitions. Generally, in swift enumerations are defined within a class or structure to support the functionality same way, by using nested types we can nest supporting classesstructuresenumerations within the definition of the type they support.

 

Swift supports a multiple nested types in enumerationsclasses, and structures. We can declare a nested class by defining one class and inside it we can declare one more class same thing we can follow for both structures and enumerations.

 

In swift for nested types we don’t have a standard syntax it’s depend upon the programmer how they declare it with own way.

Swift Nested Types Example

Following is the example of defining a nested type classes in swift programming language.

 

class Employee {

var dept = Department()

class Department{

var EmpId = 150;

var EmpName = "Suresh Dasari";

func GetDetails() -> String {

return "Id: \(self.EmpId), Name: \(self.EmpName)"

}

}

}

var emp = Employee()

print(emp.dept.GetDetails())

If you observe above example we defined a nested type class, a class within a class and accessing the properties of nested class function values. 

 

When we run the above program in swift playground we will get a result like as shown below

 

Id: 150, Name: Suresh Dasari

This is how we can use nested types in swift programming language based on our requirements.

Swift Access Nested Types

If we want to access the Nested Types outside the definition, we need to use its name with type which is nested.

 

Following is another example of defining and accessing nested types in swift programming language.

 

class Student {

enum StudentTypes {

case Intelligent

case Good

}

func name() -> StudentTypes {

return .Intelligent

}

}

class Teacher {

let student = Student()

var type: Student.StudentTypes

init() {

self.type = self.student.name()

}

}

var result = Student.StudentTypes.Good

print(result)

If you observe above example we defined a StudentTypes class as a nested class for Student class and we are accessing it by creating an instance of Student class and calling the enumeration in class to get the required values. 

 

When we run above program in swift playground we will get a result like as shown below

 

Good

This is how we can use nested types in a swift programming language to define types within the definition of another type based on our requirements.