sss sss - 4 months ago 25
Swift Question

How to replace value in array of dictionary in swift?

I have array of dictionary, I am trying to store it in NSuserdefault but as it contain

<null>
app get crash, can we replace
<null>
with ""?
Is there any way to resolve this issue?

This is my array of dictionaries:

var array = (
{
ClinicID = "<null>";
"Patient_SurveyID" = 1956;
"Patient_Treatment_PlanID" = "<null>";
PhysicianID = "<null>";
},
{
ClinicID = "<null>";
"Patient_SurveyID" = 1956;
"Patient_Treatment_PlanID" = "<null>";
PhysicianID = "<null>";
},
)

Answer

So you have an array of dictionaries

let list: [[String:Any]] = []

and each dictionary is of type [String:Any].

This is the code to replace the NSNull values into your dictionaries with ""

let list: [[String:Any] = []

let updatedDict = list.map { (dict) -> [String:Any] in
    let keysWithEmptStringValue = dict.filter { $0.1 is NSNull }.map { $0.0 }
    var dict = dict
    for key in keysWithEmptStringValue {
        dict[key] = ""
    }
    return dict
}

From NSMutableArray to [[String:Any]]

To convert your NSMutableArray to a Swift generic array please try this code

let array = NSMutableArray()
let list: [[String:Any]] = array.flatMap { $0 as? [String:Any] }

Update