swift plist 解码器全局 Spritekit
swift plist decoder global Spritekit
我想要我的 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)
}
你可以尝试写一个只加载一次的闭包
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)
}()
}
尝试 crate lazy 属性.
类似于:- 如果使用 gloabaly
var parsedConfig: 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)
}()
if in class 在 var
之前添加 lazy
我想要我的 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)
}
你可以尝试写一个只加载一次的闭包
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)
}()
}
尝试 crate lazy 属性.
类似于:- 如果使用 gloabaly
var parsedConfig: 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)
}()
if in class 在 var
之前添加 lazy