diff --git a/ObjectMapper/Core/Map.swift b/ObjectMapper/Core/Map.swift index e45f4d76..ad688a5c 100644 --- a/ObjectMapper/Core/Map.swift +++ b/ObjectMapper/Core/Map.swift @@ -63,7 +63,7 @@ public final class Map { currentValue = JSONDictionary[key] } else { // break down the components of the key that are separated by . - currentValue = valueFor(ArraySlice(key.componentsSeparatedByString(".")), collection: JSONDictionary) + currentValue = valueFor(ArraySlice(key.componentsSeparatedByString(".")), dictionary: JSONDictionary) } return self @@ -101,44 +101,50 @@ public final class Map { } } -/// Fetch value from JSON dictionary, loop through them until we reach the desired object. -private func valueFor(keyPathComponents: ArraySlice, collection: AnyObject?) -> AnyObject? { +/// Fetch value from JSON dictionary, loop through keyPathComponents until we reach the desired object +private func valueFor(keyPathComponents: ArraySlice, dictionary: [String: AnyObject]) -> AnyObject? { // Implement it as a tail recursive function. - if keyPathComponents.isEmpty { return nil } - //optional object to keep optional retreived from collection - var optionalObject: AnyObject? + if let keyPath = keyPathComponents.first { + let object = dictionary[keyPath] + if object is NSNull { + return nil + } else if let dict = object as? [String : AnyObject] where keyPathComponents.count > 1 { + let tail = keyPathComponents.dropFirst() + return valueFor(tail, dictionary: dict) + } else { + return object + } + } - //check if collection is dictionary or array (if it's array, also try to convert keypath to Int as index) - if let dictionary = collection as? [String : AnyObject], - let keyPath = keyPathComponents.first { + return nil +} - //keep retreved optional - optionalObject = dictionary[keyPath] - } else if let array = collection as? [AnyObject], - let keyPath = keyPathComponents.first, - index = Int(keyPath) { - - //keep retreved optional - optionalObject = array[index] +/// Fetch value from JSON Array, loop through keyPathComponents them until we reach the desired object +private func valueFor(keyPathComponents: ArraySlice, dictionary: [AnyObject]) -> AnyObject? { + // Implement it as a tail recursive function. + + if keyPathComponents.isEmpty { + return nil } - if let object = optionalObject { + //Try to convert keypath to Int as index) + if let keyPath = keyPathComponents.first, + let index = Int(keyPath) { + + let object = dictionary[index] + if object is NSNull { return nil - } else if let dict = object as? [String : AnyObject] where keyPathComponents.count > 1 { - let tail = keyPathComponents.dropFirst() - return valueFor(tail, collection: dict) } else if let dict = object as? [AnyObject] where keyPathComponents.count > 1 { let tail = keyPathComponents.dropFirst() - return valueFor(tail, collection: dict) + return valueFor(tail, dictionary: dict) } else { return object } } - return nil } \ No newline at end of file