What are nested types in Swift?

Swift allows nesting types within other types. This is done by defining a type in another type's definition. There is no standard syntax for this.

Let's look at a way we can nest types in Swift.

class A {
var b = B()
class B {
var C;
}
}
Syntax for the nested types in Swift

In the code above, class B is defined inside the type definition of class A. This is a very simple way to nest types in Swift. Let's look at an example.

Example

class Car {
var eng = PowerUnit()
class PowerUnit{
var PowerUnitName = "Toyota 1.8 L 2ZR-FE Dual VVT-i";
var Manufacturer = "Toyota"
var EngineName = "2ZR-FE Dual VVT-i"
var Displacement = "1798";
var Transmission = "7-speed CVT-i";
func fetchPowerUnitDetails() -> String {
return "Manufacturer: \(self.Manufacturer), EngineName: \(self.EngineName), Displacement: \(self.Displacement), Transmission: \(self.Transmission)"
}
}
}
var car = Car()
print(car.eng.fetchPowerUnitDetails())

In the code above:

  • Lines 1–15: We define a class, Car.

    • Line 2: We declare a variable eng of type PowerUnit.

    • Lines 4–14: We define a class PowerUnit inside class Car.

      • Lines 5–9: We declare some variables in the class Powerunit.

      • Lines 11–13: We define a function fetchPowerUnitDetails() in the class PowerUnit.

  • Line 16: We declare a variable of type Car.

  • Line 17: We call the fetchPowerUnitDetails() method of the eng variable of car.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved