将[String:AnyObject]类型的字典分配给[String:String]会产生nil错误

时间:2018-08-11 12:04:24

标签: ios dictionary swift3 null forced-unwrapping

嘿,我是Swift和IOS开发的新手。我面临一个被大量搜索的问题。但是没有任何解决方案。 我有[String:AnyObject]类型的字典,并想将其分配给[String:String]类型的其他字典。 Xcode显示一个错误,这是“致命错误:在展开可选val时意外发现nil” 我检查了三倍,没有零值。下面是我的代码段 字典在这里

        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
                        ] 

这里是将一本词典分配给另一本。

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

此行再次显示错误,我很确定没有nil值。

1 个答案:

答案 0 :(得分:2)

类型[String:AnyObject]的字典不能向下转换为[String:String],因为类型不兼容。

因此,dictFormData as? [String:String]的计算结果为nil,因为有条件的转换失败-您然后用nil强制解开此!并崩溃。

您显然将非字符串值放入dictFormData中,因此您将无法使用简单的下转换来获得[String:String]字典。