dictionaryswift5nsmutabledictionary

Function for Return Dictionary in swift 5


I'm working on the client Project. I've seen a function that helps to append two Parameter in a single object like this

{
 "GroupType": "string",
 "Language": "string",
 "SecondaryParameter": {
   "LocalTags": [
     {
       "Key": "string",
       "Value": "string"
     },
    {
       "Key": "string",
       "Value": "string"
     }
   ]
 }
}

The Function which is used to make parameters returns in NSMutableDictionary


 private func setBodyParams(request: Any) -> NSMutableDictionary{
        //Initialize a NSMutableDictionary
        let dataDic = NSMutableDictionary()
        //Now
        let requestMirror = Mirror(reflecting: request)
        for child in requestMirror.children{
            if child.value is Array<Any>{
                dataDic.setObject(child.value, forKey: child.label! as NSCopying)
            }else{
                dataDic.setValue(child.value, forKey: child.label!)
            }
        }
        return dataDic
    }

it returns the parameter in *NSMutableDictionary. now I have to remove this NSMutableDictionary Function and Create another function that returns Dictionary in an expected way.


Solution

  • private func setBodyParams(request: Any) -> [String : Any] {
            var dataDic: [String : Any] = [:]
            let requestMirror = Mirror(reflecting: request)
            for child in requestMirror.children {
                if child.value is Array<Any> {
                    dataDic[child.label ?? ""] = child.value
                } else {
                    dataDic[child.label ?? ""] = child.value
                }
            }
            return dataDic
        }