A nested class in Swift is a class that is defined within another class. Some key features:

  • Nested class have access to local variables or constants of the outer class unless these variables or constants are marked as static.
  • Nested class can be marked as private, fileprivate, or internal.

Here is an example of a nested class in Swift:

class OuterClass {
    private var outerProperty: Int = 0

    class NestedClass {
        let nestedProperty: String = "Nested class property"

        func nestedMethod() {
            print("This is a method in the nested class")
        }
    }

    func outerMethod() {
        print("This is a method in the outer class")
    }
}


// To use
let nestedInstance = OuterClass.NestedClass()
nestedInstance.nestedMethod()  // prints "This is a method in the nested class"
nestedInstance.outerProperty	// compile error!

With above example, the NestedClass is defined within the OuterClass, it does not have access to local variables or constants of the OuterClass unless they are marked as static.

We can also access the NestedClass from an instance of the OuterClass:

let outerInstance = OuterClass()
let nestedInstance = outerInstance.NestedClass()
nestedInstance.nestedMethod()  // prints "This is a method in the nested class"

Some scenarios of using nested class in swift

When are we going to use the Nested class:

Scenario 1: Factory Pattern

We can utilize the Nested class to implemen the factory pattern (For more details on factory pattern, please have a look at here: needone.app/factory-pattern-in-swift/). Example of factory pattern:

import Foundation

enum ProductType {
  case a
  case b
}

protocol ProductProtocol {
  func operation()
}

class ConcreteProductA: ProductProtocol {
  func operation() {
    print("Concrete Product A operation")
  }
}

class ConcreteProductB: ProductProtocol {
  func operation() {
    print("Concrete Product B operation")
  }
}

class ProductFactory {
  private init() {}
  
  class func createProduct(type: ProductType) -> ProductProtocol? {
    switch type {
    case .a:
      return ConcreteProductA()
    case .b:
      return ConcreteProductB()
    }
  }
}

// create product a
ProductFactory.createProduct(type: .a)

// create product b
ProductFactory.createProduct(type: .b)

Scenario 2: Singleton Pattern

We can also us the Nested class to create singleton in Swift.

class MySingleton {
    private class Singleton {
        static let sharedInstance = MySingleton()
    }
    
    static var shared: MySingleton {
        return Singleton.sharedInstance
    }
    
    private init() {
        // Initialization code
    }
    
    func someMethod() {
        // Perform some operations
    }
}