Swift Nested Types Example

1. Introduction

Swift enables you to define nested types, whereby you nest supporting enumerations, classes, and structures within the definition of another type. This can be handy when you want to keep related types closely tied together to enhance clarity and organize your code. Let's explore this concept with an illustrative example.

2. Source Code Example

struct University {
    var name: String
    var students: [Student]
    
    struct Student {
        var id: Int
        var name: String
        var major: Major
        
        enum Major: String {
            case computerScience = "Computer Science"
            case mechanicalEngineering = "Mechanical Engineering"
            case physics = "Physics"
            case mathematics = "Mathematics"
        }
    }
}

let john = University.Student(id: 1, name: "John", major: .computerScience)
let alice = University.Student(id: 2, name: "Alice", major: .physics)
let stanford = University(name: "Stanford", students: [john, alice])

print("\(john.name) is studying \(john.major.rawValue) at \(stanford.name).")

Output:

John is studying Computer Science at Stanford.

3. Step By Step Explanation

1. University Structure:

- We've declared a University structure, which has two properties: name and students.

- Nested within the University structure is another structure Student and within the Student, there's an enumeration Major.

2. Student Structure:

- The Student structure, nested within the University, has three properties: id, name, and major.

- major is of type Major, which is an enumeration also nested within the University structure.

3. Major Enumeration:

- This nested enum Major describes the various study majors a student can choose.

- We've defined four cases: computerScience, mechanicalEngineering, physics, and mathematics.

- The raw values of these cases are the String representations of these study majors.

4. Creating Instances:

- We create an instance of the nested Student structure by referencing it using the parent structure, like so: University.Student.

- Similarly, when referencing the nested enumeration Major, we use the Student structure as an intermediary: .computerScience.

5. Printing the Output:

- We print out the details of the student john, referencing the properties of the student and the university. 

Nested types in Swift allow for cleaner, more modular code. When types are used only within a certain context, nesting them can make the relationship between types clearer and the overall code structure more organized.