简体   繁体   中英

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

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.

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

Therefore dictFormData as? [String:String] 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM