New to IOS programming but just wondering where is the best place to put functions that I would use throughout my code. For example, I want to write a few functions to perform a POST request to a web service and return a dictionary. Maybe another function to do some calculations. Is it best to create another .swift file and put all my functions there. And what would be a good name to give the file if so?
public func postRequest() -> [String:String] { // do a post request and return post data return ["someData" : "someData"] }
The best way is to create a helper class with static functions, like this:
class Helper{ static func postRequest() -> [String:String] { // do a post request and return post data return ["someData" : "someData"] } }
Now every time you need to use postRequest
you can just use like so: Helper.postRequest()
I hope that helps you!
I usually create a separate class if I have functions that will be used by multiple classes, especially for the ones involving network operations.
If you just have separate functions that will be used, you can simply create static functions inside that class so it is easily accessible by other classes in a static way:
class DataController { static func getData() -> [String:String] { // do some operations return ["someData" : "someData"] } } let data = DataController.getData() // example
However, what often has been the case for me (especially if it involves more complicated operations) was that these network operations needed to establish an initial connection beforehand or required some initial setups, and they also performed asynchronous operations that needed to be controlled. If this is the case and you will often be calling such methods, you might want to create a singleton object that you could use throughout different classes and functions. This way, you could do the initial setup or establish an initial connection just once, and then do the rest as needed with the other functions, instead of doing them every time the function gets called.
Creating a singleton object is pretty simple in Swift:
class DataController { static let sharedInstance = DataController() // singleton object init() { // do initial setup or establish an initial connection } func getData() -> [String:String] { // do some operations return ["someData" : "someData"] } } let data = DataController.sharedInstance.getData() // example
For the name of the class, I usually name it something like DataController
or DataHelper
, but anything that makes sense as a "helper" class would work.
Hope this helps :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With