Search code examples
swiftmemoryfoundationswift-extensions

Does extension return new instance each time


Consider this case, a variable declared in an extension, like this.

extension UIViewController {
    var apiClient: APIClient {
        return APIClientImplementation()
    }
}

Does this extension return a new instance each time i call it from a different UIViewController, if so how this affects the memory ?

If not could this cause a problem, that i am getting the same instance for all the UIViewController's that i am using this instance in, and as you can tell its an APIClient instance that is used to be injected into another instance of a GateWay class, can this lead to a problem in the future ?

Note: GateWay class is class instance that i am using to execute API requests, each chunk of services has its own gateway.

I know i can use protocol to apply rules on the desired UIViewController to create instance each time.

What i am trying to achieve is to write less code with less problems in the future, and remove unnecessary chunks of code.


Solution

  • Yes, everytime you access apiClient from any viewController, a new instance of APIClient will be returned.

    As apiClient variable is get only so this itself can not cause any memory issues.