I have a plist file which has URLs in it and struct class is feeding from this plist. This struct class has static variable which I use to reach URLs in every part of the app. My question is that I'm defining this static instance with "!". I can also define it with optional ("?"). I'm not sure If I'm declaring singleton variable in right way.
Note: If something happens with reading Plist or creating struct class, app needs to display a message or something then close. So reading successfully is mandatory.
struct URLs: Codable {
let urlBaseURL: String
let urlCheckCMS: String
let urlJSON: String
static var instance: URLs!
enum CodingKeys: String, CodingKey {
case urlBaseURL = "base_url"
case urlCheckCMS = "check_cms_url"
case urlJSON = "table_json_url"
}
}
// MARK: Convenience initializers
extension URLs {
init?(data: Data) {
guard let me = try? PropertyListDecoder().decode(URLs.self, from: data) else { return nil }
self = me
URLs.instance = me
}
init?(_ plist: String, using encoding: String.Encoding = .utf8) {
guard let data = plist.data(using: encoding) else { return nil }
self.init(data: data)
}
init?(fromURL url: String) {
guard let url = URL(string: url) else { return nil }
guard let data = try? Data(contentsOf: url) else { return nil }
self.init(data: data)
}
var plistData: Data? {
return try? PropertyListEncoder().encode(self)
}
var plist: String? {
guard let data = self.plistData else { return nil }
return String(data: data, encoding: .utf8)
}
}
If I try to declare singleton as usual way;
static let instance = URLs()
It gives below error;
Cannot invoke initializer for type 'URLs' with no arguments
So I get rid of this error by writing a default init method in which I read plist file and write it to instance. However, I'm not sure with this.