From 82d740fa7fdf10e419caa1873e6d90cd0026b8cf Mon Sep 17 00:00:00 2001 From: Andrei Patru Date: Fri, 24 Mar 2017 15:05:49 -0700 Subject: [PATCH] Makes the code more readable via early returns / fatal errors in guards --- Sources/Core/SchemaLoader.swift | 44 ++++++++++++++++----------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/Sources/Core/SchemaLoader.swift b/Sources/Core/SchemaLoader.swift index 07a77b8f..ae03f0a4 100644 --- a/Sources/Core/SchemaLoader.swift +++ b/Sources/Core/SchemaLoader.swift @@ -25,30 +25,30 @@ class FileSchemaLoader: SchemaLoader { if let cachedValue = refs[schemaUrl] { return cachedValue } + // Load from local file - if let data = try? Data(contentsOf: URL(fileURLWithPath: schemaUrl.path)) { - if let jsonResult = try? JSONSerialization.jsonObject(with: data, - options: JSONSerialization.ReadingOptions.mutableContainers) { - if let jsonDict = jsonResult as? JSONObject { - let id = jsonDict["id"] as? String ?? "" - if id.hasSuffix(schemaUrl.lastPathComponent) == false { - fatalError("Invalid Schema: The value for the `id` (\(id) must end with the filename \(schemaUrl.lastPathComponent).") - } - - if let schema = FileSchemaLoader.sharedPropertyLoader(jsonDict, schemaUrl) { - refs[schemaUrl] = schema - return schema - } else { - fatalError("Invalid Schema. Unable to parse schema at URL: \(schemaUrl)") - } - } else { - fatalError("Invalid Schema. Expected dictionary as the root object type for schema at URL: \(schemaUrl)") - } - } else { - fatalError("Invalid JSON. Unable to parse json at URL: \(schemaUrl)") - } - } else { + guard let data = try? Data(contentsOf: URL(fileURLWithPath: schemaUrl.path)) else { fatalError("Error loading or parsing schema at URL: \(schemaUrl)") } + + guard let jsonResult = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) else { + fatalError("Invalid JSON. Unable to parse json at URL: \(schemaUrl)") + } + + guard let jsonDict = jsonResult as? JSONObject else { + fatalError("Invalid Schema. Expected dictionary as the root object type for schema at URL: \(schemaUrl)") + } + + let id = jsonDict["id"] as? String ?? "" + guard id.hasSuffix(schemaUrl.lastPathComponent) == true else { + fatalError("Invalid Schema: The value for the `id` (\(id) must end with the filename \(schemaUrl.lastPathComponent).") + } + + guard let schema = FileSchemaLoader.sharedPropertyLoader(jsonDict, schemaUrl) else { + fatalError("Invalid Schema. Unable to parse schema at URL: \(schemaUrl)") + } + + refs[schemaUrl] = schema + return schema } }