Reputation: 449
I want a dictionary out of my plist, which i can use in the whole gamescene. However in my solution i always have to call the parseConfig function in order to get a dictionary from the 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)
}
Upvotes: 1
Views: 76
Reputation: 91
try crate lazy property.
Something like: - if use 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 add lazy before var
Upvotes: 1
Reputation: 100541
You can try to write a closure to load only once
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)
}()
or inside a singleton in all the app
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)
}()
}
Upvotes: 1