JuicyFruit JuicyFruit - 3 months ago 8
iOS Question

class instance to all ViewControllers

I wish to avoid writing "let APIHelper = API()" in every UIViewController, instead I did this:

extension UIViewController {
func APIHelper() -> API {
let api = API()
return api
}
}


and now it is working like self.APIHelper().callMethod(), but I'm not really sure if it is the way to do it. any tips on best practice?

Answer

Your extension useless, since it just same as calling API() everytime:

self.APIHelper().callMethod()
self.APIHelper().callSecondMethod() //here you created another API instance

same as

API().callMethod()
API().callSecondMethod()

If API is singletone, idea looks ok, but in swift you usually create singletone with static constant:

class API {
    static let sharedAPI = API()
    //...
}

and access to it like this:

API.sharedAPI.callMethod()
API.sharedAPI.callSecondMethod() //now called in same API instance

If you don't want to write API.sharedAPI everytime, then you can use:

Your extension

extension UIViewController {
    var apiHelper: API {return API.sharedAPI}
}

Not recommended as @NickCatib explained.

Base view controller

as @NickCatib suggested (easier with variable):

class BaseViewController: UIViewController {
    // some of the code you might need
    var apiHelper: API {return API.sharedAPI}
}

Protocol

If you use API in view controllers time to time, can be better declare protocol

protocol API {
    var apiHelper: API {get}
}

with default implementation

extension API {
    var apiHelper: API {return API.sharedAPI}
}

and connect it to your viewController only when needed

class ViewControllerThatNeedsAPI: UIViewController, API {
    // apiHelper avalible here
}

With all three ways you access your API like this:

apiHelper.callMethod()