Where to put reusable functions in IOS Swift?

前端 未结 5 894
[愿得一人]
[愿得一人] 2020-12-13 03:53

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 perfo

5条回答
  •  伪装坚强ぢ
    2020-12-13 04:21

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

提交回复
热议问题