Get Dictionary after removing all null values :- 

extension Dictionary where Value: Any {
    
    func nullsRemoved() -> Dictionary {
        var dicOriginal = self
        
        let keysToRemove = Array(dicOriginal.keys).filter { dicOriginal[$0] is NSNull }
        for key in keysToRemove {
            dicOriginal.removeValue(forKey: key)
        }
        
        return dicOriginal
    }
}

ex :-

dicResponse = dicResponse.nullsRemoved()

 


Get value if available from dictionary to solve crash issue :-

extension Dictionary {
    
    func getValueIfAvilable(_ key: Key) -> Value? {
        // if key not found, replace the nil with
        // the first element of the values collection
        if let val = self[key] {
            return val
        }
        return nil
        // note, this is still an optional (because the
        // dictionary could be empty)
    }
}

ex :-

self.txtField.text = pdictResponse.getValueIfAvilable(KTITLE) as? String

You may also like

Leave a Reply