From 269ba193c7a925e9c10e43afb00468fb34afba6a Mon Sep 17 00:00:00 2001 From: Oleksii Dykan Date: Tue, 19 Sep 2017 21:14:47 +0200 Subject: [PATCH] Add init with json to Dictionary --- SwiftyJSONModel/JSONObject.swift | 12 +----------- SwiftyJSONModel/JSONTypes.swift | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/SwiftyJSONModel/JSONObject.swift b/SwiftyJSONModel/JSONObject.swift index 61d11ba..6d72639 100644 --- a/SwiftyJSONModel/JSONObject.swift +++ b/SwiftyJSONModel/JSONObject.swift @@ -96,17 +96,7 @@ public extension JSONObject where PropertyType.RawValue == String { } private func value(for keyPath: [PropertyType]) throws -> [String: T] { - return try value(for: keyPath) { - var result: [String: T] = [:] - try $0.dictionaryValue().forEach({ key, json in - do { - result[key] = try T(json: json) - } catch let error as JSONModelError { - throw JSONModelError.invalidValueFor(key: key, error) - } - }) - return result - } + return try value(for: keyPath) { try Dictionary(json: $0) } } // MARK: - Value for keypath - Date diff --git a/SwiftyJSONModel/JSONTypes.swift b/SwiftyJSONModel/JSONTypes.swift index 112f307..6799eb3 100644 --- a/SwiftyJSONModel/JSONTypes.swift +++ b/SwiftyJSONModel/JSONTypes.swift @@ -134,6 +134,20 @@ public extension Dictionary where Key == String, Value: JSONRepresentable { } } +public extension Dictionary where Key == String, Value: JSONInitializable { + public init(json: JSON) throws { + var result: [String: Value] = [:] + try json.dictionaryValue().forEach({ key, json in + do { + result[key] = try Value(json: json) + } catch let error as JSONModelError { + throw JSONModelError.invalidValueFor(key: key, error) + } + }) + self = result + } +} + public extension Date { public func json(with transformer: DateTransformer) -> String { return transformer.string(form: self)