Skip to content

Commit 6844af0

Browse files
author
Josh Smith
committed
Add helper methods to CreatableFromJSON extension
Include two new methods in the CreatableFromJSON protocol extension that simplify turning JSON arrays into data model arrays. The methods that previously existed were only really suitable for use when the arrays were inside a JSON dictionary (which helps keep the failable initializers clean and simple). These new methods are useful outside of that context. This improvement was brought to my attention by Andrew Duncan http://andrewduncan.net/
1 parent 84c8490 commit 6844af0

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

json2swift/swift-code-templates.swift

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,12 @@ private let codeTemplateForCreatableWithJSON = [
4242
" /// - Returns: `nil` if the JSON array is missing or if there is an invalid/null element in the JSON array.",
4343
" static func createRequiredInstances(from json: [String: Any], arrayKey: String) -> [Self]? {",
4444
" guard let jsonDictionaries = json[arrayKey] as? [[String: Any]] else { return nil }",
45+
" return createRequiredInstances(from: jsonDictionaries)",
46+
" }",
47+
"",
48+
" /// Attempts to produce an array of instances of the conforming type based on an array of JSON dictionaries.",
49+
" /// - Returns: `nil` if there is an invalid/null element in the JSON array.",
50+
" static func createRequiredInstances(from jsonDictionaries: [[String: Any]]) -> [Self]? {",
4551
" var array = [Self]()",
4652
" for jsonDictionary in jsonDictionaries {",
4753
" guard let instance = Self.init(json: jsonDictionary) else { return nil }",
@@ -54,6 +60,12 @@ private let codeTemplateForCreatableWithJSON = [
5460
" /// - Returns: `nil` if the JSON array is missing, or an array with `nil` for each invalid/null element in the JSON array.",
5561
" static func createOptionalInstances(from json: [String: Any], arrayKey: String) -> [Self?]? {",
5662
" guard let array = json[arrayKey] as? [Any] else { return nil }",
63+
" return createOptionalInstances(from: array)",
64+
" }",
65+
"",
66+
" /// Attempts to produce an array of instances of the conforming type, or `nil`, based on an array.",
67+
" /// - Returns: An array of instances of the conforming type and `nil` for each invalid/null element in the source array.",
68+
" static func createOptionalInstances(from array: [Any]) -> [Self?] {",
5769
" return array.map { item in",
5870
" if let jsonDictionary = item as? [String: Any] {",
5971
" return Self.init(json: jsonDictionary)",

0 commit comments

Comments
 (0)