swift plist解码器全局Spritekit

时间:2018-10-20 18:12:51

标签: ios swift sprite-kit plist

我想从我的plist中删除一个词典,我可以在整个游戏场景中使用它。但是,在我的解决方案中,我总是必须调用parseConfig函数才能从plist中获取字典。

struct Config: Decodable {
    private enum CodingKeys: String, CodingKey {
        case zPositions, enemy, player
    }

    let zPositions: [String:Double]
    let enemy: [String:[String:Double]]
    let player: [String:[String:Double]]
}

func parseConfig() -> Config {
    let url = Bundle.main.url(forResource: "Config", withExtension: "plist")!
    let data = try! Data(contentsOf: url)
    let decoder = PropertyListDecoder()
    return try! decoder.decode(Config.self, from: data)
}

2 个答案:

答案 0 :(得分:1)

您可以尝试编写一个仅加载一次的闭包

lazy var myConfig : Config  = {  
      let url = Bundle.main.url(forResource: "Config", withExtension: "plist")!
      let data = try! Data(contentsOf: url)
      let decoder = PropertyListDecoder()
      return try! decoder.decode(Config.self, from: data)
}()

或在所有应用中的单例中

class Service {

 static let shared = Service()

  lazy var myConfig : Config  = { 

      let url = Bundle.main.url(forResource: "Config", withExtension: "plist")!
      let data = try! Data(contentsOf: url)
      let decoder = PropertyListDecoder()
      return try! decoder.decode(Config.self, from: data)
  }()

}

答案 1 :(得分:1)

尝试板条箱的懒惰属性。

类似于:-如果使用gloabaly

LLVMFuzzerTestOneInput

如果在课堂上在var之前添加懒惰