Any problem when I declare a class inside another class?

Viewed 74

I am bit confused If any memory related issue happen when I declare classes like below by using Swift programming language, The main purpose is to reduce real-time compile process. Because my system goes very slow If I declare class globally that is using in only one class.

  class Person {
    private var edu: Education? //network sync
    let name: String
    init(name: String) {
        self.name = name
    }
    private class Education { }
}

Here I used above class person

class SectionA {
    let amy: Person = .init(name: "Amy")
    let rachel: Person = .init(name: "Rachel")
    let sarah: Person = .init(name: "Sarah")
    let jack: Person = .init(name: "Jack")
}

What I am worried about is with class Education. Is the above class Person can take more process or memory than declaring class Education outside of Person like below?

class Person {
    private var edu: Education?
    let name: String
    
    init(name: String) {        
        self.name = name
    }
}

class Education { }

Thank you!

2 Answers

Putting a class inside a class the way you have has exactly one impact: it changes the naming of the nested class. Instead of being called Module.Education, it's now Module.Person.Education.

That can be useful for organizing things. If Eduction can only apply to Person, maybe you want to cluster those concepts together and keep Education from polluting the top-level name-space. Other than that, it has no impact. It has no impact on visibility. It has no impact on access controls.

Given your comment that the "main purpose is to reduce real-time compile process," this has no important impact. It might slightly increase or decrease compile times for a particular code base, but the difference is unpredictable and likely small. Marking it private inside vs outside the class will have no impact at all (marking it private generally has very little impact, since the compiler is very good at marking things private when appropriate).

I believe what you're looking for is to create a subclass which would inherit all the properties of your main class.

From my understanding it should look like this below:

class Person{
    

    var edu: Education? //network sync
    
    let name: String
    
    init(name: String) {
    
        self.name = name
    }
    
}

class Education: Person {


//insert info here

}
Related