Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 592 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Where to put reusable functions in IOS Swift?

#1
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"]
}
Reply

#2
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()`
Reply

#3
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
Reply

#4
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.
Reply

#5
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]
}
}

Reply

#6
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 :)
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through