Ios 从Swift的单个类访问常用代码块的正确方法

Ios 从Swift的单个类访问常用代码块的正确方法,ios,swift,code-reuse,Ios,Swift,Code Reuse,我想为一些常量值和常用代码块实现一个helper类。在下列用法之间,哪一种是正确的方法 将它们定义为静态let值 将它们定义为类函数 class Constants { // 1: defining them as static let values static let storyboardA = UIStoryboard(name: "StoryboardA", bundle: nil) static let storyboardB = UIStoryboard(n

我想为一些常量值和常用代码块实现一个helper类。在下列用法之间,哪一种是正确的方法

  • 将它们定义为静态let值
  • 将它们定义为类函数

    class Constants 
    {
        // 1: defining them as static let values
        static let storyboardA = UIStoryboard(name: "StoryboardA", bundle: nil)
        static let storyboardB = UIStoryboard(name: "StoryboardB", bundle: nil)
        static let rootVC = UIApplication.sharedApplication().delegate?.window!!.rootViewController
    
       // 2: OR defining them as class functions
       class func getStoryboardA() -> UIStoryboard {
          return UIStoryboard(name: "storyboardA", bundle: nil)
       }
    
       class func getStoryboardB() -> UIStoryboard {
          return UIStoryboard(name: "StoryboardB", bundle: nil)
       }
    
       class func getRootVC() -> UIViewController? {
          return UIApplication.sharedApplication().delegate?.window!!.rootViewController
       }
    }
    

  • 您的示例做了不同的事情(实例化一个新实例与反复使用相同的实例)。我会使用这些方法,并在私有变量中缓存重用的对象

    不过,我强烈建议不要使用这种方法。一开始它看起来很诱人,但长期以来它带来了巨大的成本。这会导致非常紧密的代码耦合和糟糕的代码重用。测试将更加困难

    你的助手类会越来越大,它没有一个“主题”。它负责你应用程序中最不同的事情。你的应用程序中的一个部分不太可能需要故事板,其他的部分也不需要

    大多数时候,如果你需要到处访问这些东西,你的应用程序设计将从重构中获益。例如,您几乎不需要访问应用程序委托。这是一个方便的“参考点”,可以很容易地用不属于他们的代码纠缠它(在那里,完成了,学到了我的教训)


    一种更合理的方法是创建单独的helper类并将它们放入using类中,而我也不会创建它们的成员类方法

    >>“实例化一个新实例与反复使用相同的实例”。你能说得更具体些吗?据我所知,
    static let
    将仅被实例化once@AnilVarghese是的,与之相反,给定的类方法将返回新对象。哦,你的意思是,你将以这样一种方式使用方法,它将返回私有静态变量。更像是结合了OP的两种方法。也许你可以展示一些示例代码,会更有帮助