Skip to content

Commit

Permalink
Merge pull request #35 from alickbass/array-dict-json-init
Browse files Browse the repository at this point in the history
Array dict json init
  • Loading branch information
Oleksii Dykan authored Sep 19, 2017
2 parents 9d20a89 + 269ba19 commit 3ee5b14
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 20 deletions.
22 changes: 2 additions & 20 deletions SwiftyJSONModel/JSONObject.swift
Original file line number Diff line number Diff line change
Expand Up @@ -87,15 +87,7 @@ public extension JSONObject where PropertyType.RawValue == String {
}

private func value<T: JSONInitializable>(for keyPath: [PropertyType]) throws -> [T] {
return try value(for: keyPath) {
try $0.arrayValue().lazy.enumerated().map({ index, json in
do {
return try T(json: json)
} catch let error as JSONModelError {
throw JSONModelError.invalidValueFor(key: String(index), error)
}
})
}
return try value(for: keyPath) { try Array(json: $0) }
}

// MARK: - Value for keypath - Dictionary
Expand All @@ -104,17 +96,7 @@ public extension JSONObject where PropertyType.RawValue == String {
}

private func value<T: JSONInitializable>(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
Expand Down
26 changes: 26 additions & 0 deletions SwiftyJSONModel/JSONTypes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,18 @@ public extension Array where Element: JSONRepresentable {
}
}

public extension Array where Element: JSONInitializable {
public init(json: JSON) throws {
self = try json.arrayValue().lazy.enumerated().map({ index, json in
do {
return try Element(json: json)
} catch let error as JSONModelError {
throw JSONModelError.invalidValueFor(key: String(index), error)
}
})
}
}

struct JSONDict<T: JSONRepresentable>: JSONRepresentable {
let dict: [String: T]

Expand All @@ -122,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)
Expand Down

0 comments on commit 3ee5b14

Please sign in to comment.