Assigning a dictionary of type [String:AnyObject] to [String: String] gives nil error

44 Views Asked by At

Hey I am newbie in Swift & IOS development. I am facing an issue searched a lot. But didn't got any solution. I have dictionary of type [String: AnyObject] and wants to assign it to an other dictionary of type [String:String]. Xcode Shows an error which is this "Fatal error: Unexpectedly found nil while unwrapping an Optional val" I tripled checked there is no nil value. Below here is my code snippet Dictionary is here

        let dictFormData = ["name": endorsement.name,
                            "designation":endorsement.designation,
                            "location": endorsement.location,
                            "region": endorsement.region,
                            "effectiveDateString":endorsement.effectiveDate,
                            "marriageDateString": "ss" ,
                            "genderId": String(format: "%ld", selectedGenderLookUpId),
                            "relationId": String(format: "%ld", selectedRelationLookUpId),
                            "plan": "ss",
                            "employeeId": AICLPolicyModel.getSelectedPolicy()?.employeeID as Any,
                            "requestTypeId": 35,
                            "policyId": AICLPolicyModel.getSelectedPolicy()?.policyID as Any,
                            "isEmployee": isemployee,
                            "filePath":"ss",
                            "fileName": "ss",
                            "empRemarks": endorsement.remarks,
                            "hrRemarks": "ss",
                            "adminRemarks": "ss",
                            "memberCode": AICLPolicyModel.getSelectedPolicy()?.memberCode as Any,
                            "requestStatusId": 32,
                            "customerId":  AICLPolicyModel.getSelectedPolicy()?.clientID as Any
                        ] 

Here is assigning of one dictionary to other.

   let formData = (dictFormData as? [String : String])!

At this line it shows error once again I am quite sure there is no nil value.

1

There are 1 best solutions below

2
On

A dictionary of type [String:AnyObject] cannot be downcast to [String:String] since the types are incompatible.

Therefore dictFormData as? [String:String] evaluates to nil because the conditional downcast fails - you are then force unwrapping this nil with ! and you get a crash.

You are clearly putting non-String values into dictFormData, so you won't be able to use a simple downcast to get a [String:String] dictionary.