Swift Nested Types

  Total Views : 198
  Comments : 0
  Keywords : Swift nested types are used to nest types within the definition of the type they support, Swift nested types to nest other types in our type definition

Here we will learn nested types in swift with examples and how to use and access swift nested types in enumerations, classes and structures with examples.

Swift Nested Types

In swift, Nested types are the types which 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 support a multiple nested types in enumerationsclasses and structures. We can declare a nested class by defining a 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 above program in swift playground we will get 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 result like as shown below

 

Good

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

 
 

NEXT

Swift Protocols  
 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User