codable

decode Json string to class object Swift

血红的双手。 提交于 2019-12-12 12:24:21
问题 private func createWeatherObjectWith(json: Data, x:Any.Type ,completion: @escaping (_ data: Any?, _ error: Error?) -> Void) { do { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let weather = try decoder.decode(x.self, from: json) return completion(weather, nil) } catch let error { print("Error creating current weather from JSON because: \(error.localizedDescription)") return completion(nil, error) } } Here I write above code to decode Json string to class

Codable : does not conform to protocol 'Decodable'

坚强是说给别人听的谎言 提交于 2019-12-12 10:53:55
问题 Not able to figure why my class does not conform to Codable Please not that in my case I do not need to implement the methods encode and decode . public class LCLAdvantagePlusJackpotCache: Codable { public let token: String public let amount: NSNumber public let member: Bool public init(token: String, amount: NSNumber, member: Bool) { self.token = token self.amount = amount self.member = member } enum CodingKeys: String, CodingKey { case token, amount, member } } 回答1: It's because NSNumber is

How to retrieve a value from JSON Object Swift 4

老子叫甜甜 提交于 2019-12-11 17:20:01
问题 I am trying to decode JSON object using Codable with Swift 4: { USD: { "15m": 9977.49, last: 9977.49, buy: 9979.36, sell: 9975.62, symbol: "$" }, AUD: { "15m": 13181.69, last: 13181.69, buy: 13184.16, sell: 13179.22, symbol: "$" }, TBD: { "15m": 13181.69, last: 13181.69, buy: 13184.16, sell: 13179.22, symbol: "$" } } This is what I've done so far with a model of an object: struct Currency: Codable { let fifteenMin: Double? let last: Double? let buy: Double let sell: Double let symbol: String

Pass A Generic Codable Type as Parameter to a Method for Saving to Realm

ⅰ亾dé卋堺 提交于 2019-12-11 17:04:53
问题 I am trying to create a generic method for decoding some JSON data. I need to cast the JSON data into Objects for later saving in Realm. For example: Getting the makes, models, colors, and body types of vehicles. In each of my JSON calls to the results are formatted exactly the same (See my structs at the end of the question). For brevity, I am only showing you Makes and Models, but Colors and Body Types are exactly the same, just with the name changes. I currently have four methods that I

Swift Codable: decode dictionary with unknown keys

偶尔善良 提交于 2019-12-11 15:59:52
问题 Codable is great when you know the key formatting of the JSON data. But what if you don't know the keys? I'm currently faced with this problem. Normally I would expect JSON data to be returned like this: { "id": "<123>", "data": [ { "id": "<id1>", "event": "<event_type>", "date": "<date>" }, { "id": "<id2>", "event": "<event_type>", "date": "<date>" }, ] } But this is what I'm aiming to decode: { "id": "123", "data": [ { "<id1>": { "<event>": "<date>" } }, { "<id2>": { "<event>": "<date>" } }

NSUserDefaults: storing struct/class with only property list compliant types, in a readable format

╄→гoц情女王★ 提交于 2019-12-11 15:36:08
问题 Suppose a dictionary is stored in UserDefaults according to the following code: UserDefaults.standard.set(["name": "A preset", "value": 1], forKey: "preset") The plist that results from running this command is: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>preset</key> <dict> <key>name</key> <string>A preset</string> <key>value</key> <integer>1</integer> </dict> <

How to use Codable protocol for an enum with other enum as associated value (nested enum)

╄→尐↘猪︶ㄣ 提交于 2019-12-11 14:42:32
问题 I asked a question yesterday on how to save a nested enum inside UserDefaults . I am trying to use the Codable protocol for this, but not sure if I am doing it correctly. Here is again the enum I want to store -> UserState : enum UserState { case LoggedIn(LoggedInState) case LoggedOut(LoggedOutState) } enum LoggedInState: String { case playing case paused case stopped } enum LoggedOutState: String { case Unregistered case Registered } Here are the steps I did so far: Conform to Codable

List is not conforming to Encodable

蹲街弑〆低调 提交于 2019-12-11 07:35:46
问题 So, I'm using realm and I have the following relationship between two models: A unit has many tests : // Unit model class Unit: Object, Decodable { @objc dynamic var id: String = "" ... let tests = List<Test>() enum CodingKeys: String, CodingKey { case id ... //case tests = "complete_control_tests" } convenience required init(from decoder: Decoder) throws { self.init() let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decode(String.self, forKey: .id) ... if

Generic Decoders in Swift 4

萝らか妹 提交于 2019-12-11 06:34:52
问题 Currently I'm using this code to handle decoding some data: private func parseJSON(_ data: Data) throws -> [ParsedType] { let decoder = JSONDecoder() let parsed = try decoder.decode([ParsedType].self, from: data) return parsed } private func parsePlist(_ data: Data) throws -> [ParsedType] { let decoder = PropertyListDecoder() let parsed = try decoder.decode([ParsedType].self, from: data) return parsed } Is there a way to create a generic method that ties all this repeated code together?

Make a (deep) copy of an Object that conforms to Codable

匆匆过客 提交于 2019-12-11 06:17:56
问题 I have an object that subclasses Object from Realm, and conforms to Codable in order to convert to and from JSON when talking to an API. How can I make a deep copy (include children objects) by leveraging the Codable protocol? 回答1: This will make a deep copy of an object leveraging the Codable protocol. As mentioned by @itai-ferber it will have a high overhead when compared to NSCopying . class MyObject: Object, Codable { /* details omitted */ var children = List<ChildObject>() func copy()