Reputation: 2122
I came from Android background and I'm new to Swift. I want to know how to use common functions in ViewControllers with DRY principles.
I need all of my ViewControllers to call following functions from one place:
isNetworkAvailable() //check app has internet return boolean
getLoggedinUser() //return logged in user object which I set before
showAlert(message:String) //display a popup
startLoader() // display a loader
stopLoader() // stop loader
As you can see these methods are global and I need to reuse them many times. So I don't want to copy paste the same code over and over again.
In Android I simply make one BaseActivity and put all those methods in it. Later I will extend the BaseActivity into SubActivities and inherit those common methods.
I'm not sure how to do this in "IOS Swift" as all the ViewControllers are attached to StoryBoard.
Can you please tell me what is the best way to achieve this? How does professional Swift developers handle situations like this?
(Please note - I don't want to delete story board and manually create UI elements.)
Thanks in Advance!
Upvotes: 0
Views: 493
Reputation: 556
Create a CommonFunctions
named public class (just a suggestion you can name it any class name which you want) extend it from NSObject and import UIKit
Module in it because I think you also want to perform UI Operations in it like startLoader() & stopLoader()
then you can write static global methods which you are mentioned in your question.
You can call then using CommonFunctions.methodName()
.
Or if you don't want to make static functions then create object of CommonFunctions
class wherever you want to access those global methods and call the method which you want.
Upvotes: 1