Swift Programming – Nested Types

In this tutorial you’ll learn about nested types in Swift. To follow along, it is recommended to have a Mac and the Xcode IDE installed on it. This tutorial makes use of the Xcode playground for compilation of the Swift codes. If you do not have a Mac, you may try using the open-source code editors which support different operating systems such as AtomSublimeText or VSCode.

Nested Types

You can define enumerations, structures and classes within a specific type. This is known as nested types. Let’s try an example for a better understanding of this concept.

struct Smartphone {
    // Smartphone's nested enumeration
    enum Brand {
        case Apple, Samsung
        
        // Brand's nested structure
        struct Specification {
            let batteryLifeVideoPlayback: Int
        }
        
        // Brand's property
        var models: [String] {
            switch self {
            case .Apple:
                return ["iPhone 12 Pro", "iPhone 12 Pro Max"]
            case .Samsung:
                return ["Galaxy Note20", "Galaxy Note20 Ultra"]
            }
        }
        
        // Brand's property
        var details: [Specification] {
            switch self {
            case .Apple:
                return [Specification(batteryLifeVideoPlayback: 17), Specification(batteryLifeVideoPlayback: 20)]
            case .Samsung:
                return [Specification(batteryLifeVideoPlayback: 19), Specification(batteryLifeVideoPlayback: 19)]
            }
        }
    }
    
    // Smartphone's properties
    let brand: Brand
    var description: String {
        var text = ""
        
        for i in brand.models.indices {
            text += "\(brand) has the model \(brand.models[i]) with battery life for video playback time of \(brand.details[i].batteryLifeVideoPlayback) hours.\n"
        }
        
        return text
    }
}

let apple = Smartphone(brand: .Apple)
print(apple.description)

let samsung = Smartphone(brand: .Samsung)
print(samsung.description)

In our example above, we defined a structure named Smartphone. Inside our structure we defined an enumeration named Brand, one stored property brand of type Brand and one computed property description of type String. Inside our enumeration Brand, we defined two enumeration cases, a structure named Specification, two computed properties, models of type [String] and details of type [Specification].

Reference

https://docs.swift.org/swift-book/LanguageGuide/NestedTypes.html