【问题标题】:How to create a proper singleton for Dictionary in Swift 2如何在 Swift 2 中为 Dictionary 创建正确的单例
【发布时间】:2016-08-13 10:59:32
【问题描述】:

我有以下代码

class Test: UIViewController {
  var imagesOfChef = [Int : chefImages]()
    struct chefImages {
          var objidChef: String!
          var imageChef: UIImage!
      }

}

用户一打开应用程序,我就会填写这本词典。 但我希望它也可以在其他视图(swift 文件)中使用

让我们在这堂课上说

class Test2: UIViewController{

}

如何为这个 Dictionary 创建一个单例,以便其他视图可以使用它?

感谢您的宝贵时间!

【问题讨论】:

标签: ios swift swift2 ios9


【解决方案1】:

您可以使用静态属性:

static var imagesOfChef = [Int : chefImages]()

然后你使用:

Test.imagesOfChef 

但我建议尽可能避免使用静态方法,如果 Test 有 Test2,您可以使用 prepare segue 或从外部分配属性。

【讨论】:

    【解决方案2】:

    StackOverlow 上有很多关于如何创建 Singleton 的示例。

    不管怎样,你的代码应该是这样的

    struct Chef {
        let id: String
        let image: UIImage
    }
    
    final class Singleton {
        static let sharedInstance = Singleton()
        private init() { }        
        var dict = [Int: Chef]()
    }
    

    现在您可以在应用的任何来源中使用它

    Singleton.sharedInstance.dict[1] = Chef(id: "1", image: UIImage())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-25
      • 2018-06-02
      • 2023-03-08
      • 2016-07-11
      • 2021-09-13
      • 1970-01-01
      • 2014-12-30
      相关资源
      最近更新 更多