Where to put reusable functions in IOS Swift?

IosSwift

Ios Problem Overview


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"]
}

Ios Solutions


Solution 1 - Ios

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!

Solution 2 - Ios

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 :)

Solution 3 - Ios

For reusable functions it depends what I decide to use. For this specific case I use a separate file, because posting to a backend will become more complicated when the application evolves. In my app I use a backend class, with all kinds of helper classes:

struct BackendError {
    var message : String
}

struct SuccessCall {
    var json : JSON
    
    var containsError : Bool {
        if let error = json["error"].string {
            return true
        }
        else {
            return false
        }

    }
}

typealias FailureBlock  = (BackendError) -> Void
typealias SuccessBlock  = (SuccessCall) -> Void

typealias AlamoFireRequest = (path: String, method: Alamofire.Method, data: [String:String]) -> Request
typealias GetFunction = (path: String , data: [String : String], failureBlock: FailureBlock, successBlock: SuccessBlock) -> Void

class Backend {
   func getRequestToBackend (token: String )(path: String , data: [String : String], failureBlock: FailureBlock, successBlock: 

}

For other cases I often use extensions on Swift classes. Like for getting a random element from an Array.

extension Array {
    func sampleItem() -> T {
        let index = Int(arc4random_uniform(UInt32(self.count)))
        return self[index]
    }
}

Solution 4 - Ios

This very old question but I would like to chirp some more points. There are a few option, basically you can write your utility functions in Swift -

A class with static function. For example

class CommonUtility {
      static func someTask() {
      }    
}
// uses
CommonUtility.someTask()

Also, you can have class method's as well instead of static method but those functions can be overridden by subclasses unlike static functions.

class CommonUtility {
      class func someTask() {
      }    
}
// uses
CommonUtility.someTask()

Secondly, you can have Global functions as well, that are not part of any class and can be access anywhere from your app just by name.

func someTask() {
} 

Though, selecting one over other is very subjective and I thing this is ok to make a class with static function in this particular case, where you need to achieve networking functionality but if you have some functions which perform only one task than Global function is a way to go because Global functions are more modular and separate out single tasks for a single function.

In case of static functions, if we access one of the static member, entire class gets loaded in memory. But in case of global function, only that particular function will be loaded in mem

Solution 5 - Ios

You can create a separate swift class, might name it WebServicesManager.swift, and write all methods related to web requests in it.

You can use class methods, or singleton pattern to access the methods.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex LacayoView Question on Stackoverflow
Solution 1 - IosIcaroView Answer on Stackoverflow
Solution 2 - IosDennisView Answer on Stackoverflow
Solution 3 - IosRaymondView Answer on Stackoverflow
Solution 4 - IosSuryakant SharmaView Answer on Stackoverflow
Solution 5 - Iossudhanshu-shishodiaView Answer on Stackoverflow