Where to put reusable functions in IOS Swift?

前端 未结 5 901
[愿得一人]
[愿得一人] 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-13 04:16

    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

提交回复
热议问题