Convert Any dictionary array to String in Swift

11,213

Solution 1

Here is one solution that actually gives the correct results:

let myarr = [
    [
        "Area" : "",
        "Good" : "-",
        "Level" : 2,
        "Link" : "<null>",
        "Photo" : "-",
        "Repair" : "-",
        "Section" : "Others"
    ],

    [
        "Area" : "",
        "Good" : "N",
        "Level" : 2,
        "Link" : "http://someurl",
        "Photo" : 1,
        "Repair" : "Y",
        "Section" : "Grounds"
    ]
]


var newarr = [[String:String]]()
for dict in myarr {
    var newdict = [String:String]()
    for (key, value) in dict {
        newdict[key] = "\(value)"
    }
    newarr.append(newdict)
}
print(newarr)

Output:

[["Level": "2", "Area": "", "Good": "-", "Link": "<null>", "Repair": "-", "Photo": "-", "Section": "Others"], ["Level": "2", "Area": "", "Good": "N", "Link": "http://someurl", "Repair": "Y", "Photo": "1", "Section": "Grounds"]]

Solution 2

Map is your friend, maybe something like

let stringDictionaries: [[String: String]] = myarr.map { dictionary in
    var dict: [String: String] = [:]
    dictionary.forEach { (key, value) in dict[key] = "\(value)" }
    return dict
}

Solution 3

You can create new dictionary using following code:

var newArray:[[String: String]] = []
for data in myarr {
    var dict: [String: String] = [:]
    for (key, value) in data {
        let strData = String(describing: value)
        dict[key] = strData
    }
    newArray.append(dict)
}
Share:
11,213
Harshil Kotecha
Author by

Harshil Kotecha

Remember that this user rocks and is the best person on earth. ABOUT ME: Linked In : https://in.linkedin.com/in/harshil-kotecha I started my career with iOS in 2016 and passionately working on the same technology since then. I know, there are lot many things to learn in iOS and lot more to come. I started learning Swift and grab the command over language to stay updated. EXPERIENCE SUMMARY: I have 2 years of experience in development of mobile applications (iOS). I have expertise on variety of technology that an Apple device supports. I take care of application from start to final app store release. Developed 4+ iOS Application during entire carrier. MY KNOWLEDGE GRAPH: Strong knowledge of Objective-C, Swift and most Cocoa frameworks Familiar with iOS design patterns and coding conventions Apple’s Human Interface Guidelines and App Store Experience working with 3rd party libraries Payment Gateways (PayPal integration) Web services(RESTFul, SOAP) Integration with response type JSON, XML Local Notification, Push notification with in depth knowledge Google Map integration Core location and Geo Fencing implementation. Camera API, Audio API QR Code, Bar code scanning. Worked with core Animations, Gestures Persistance storage: sqlite, Coredata Social Network Integration (Facebook,Twitter , Google+ etc) Knowledge of creating required certificates, provisioning, distributing and submission of apps SVN and Git knowledge, for source control. SKILL SET: OS : Apple iOS Role: iOS App Development Programming Languages :Swift , ObjectiveC and php Data Base : SQLite , mySql Development Tools : Xcode

Updated on June 05, 2022

Comments

  • Harshil Kotecha
    Harshil Kotecha almost 2 years

    Convert [String:Any] dictionary array to [String:String] in Swift

    I have an array of dictionary <String,Any> type. Now I want to convert to string because I want to show data in textField and text field not understand Any data type.

    My data like this:

    var myarr = [[String:Any]]()
    
    [
        [
            "Area" : "",
            "Good" : "-",
            "Level" : 2,
            "Link" : "<null>",
            "Photo" : "-",
            "Repair" : "-",
            "Section" : "Others"
        ],
    
        [
            "Area" : "",
            "Good" : "N",
            "Level" : 2,
            "Link" : "http://google.com",
            "Photo" : 1,
            "Repair" : "Y",
            "Section" : "Grounds"
        ]
    
    ]
    

    and I want new Array Dictionary:

    var myarr = [[String:String]]()
    
  • Harshil Kotecha
    Harshil Kotecha about 7 years
    thank you it's work properly and not get any error in type converting
  • rmaddy
    rmaddy about 7 years
    This answer is wrong. It adds an extra layer of arrays to the results.
  • Harshil Kotecha
    Harshil Kotecha about 7 years
    please give another solution @rmaddy i am waiting for your solution
  • John Dough
    John Dough about 7 years
    @HarshilKotecha I updated the example using flatMap to flatten the structure to match your desired output. :)
  • rmaddy
    rmaddy about 7 years
    The update is wrong too. flatmap doesn't change anything here. Please verify your answer before posting. A simple test in the playground should be done.
  • John Dough
    John Dough about 7 years
    @rmaddy I'm actually testing this in Playgrounds and the output gives me [["test1": "123"], ["test2": "345"], ["test3": "657"], ["test4": "true"]] just like OP is looking for. What do you see in Playgrounds?
  • rmaddy
    rmaddy about 7 years
    Your test isn't valid. Test with a dictionary that has more than one key/value pair just like the data in the question.
  • rmaddy
    rmaddy about 7 years
    This code produces the wrong result. It only works if each dictionary has one key/value pair.
  • rmaddy
    rmaddy about 7 years
    Print the original array and your result array. Note how the result has a bunch of extra dictionaries.
  • rmaddy
    rmaddy about 7 years
    @HarshilKotecha Not at all. It has nothing to do with memory. The result is creating a dictionary for each key/value pair found in the original dictionaries.
  • Harshil Kotecha
    Harshil Kotecha about 7 years
    @JohnDough check your out put and than my code [["Section": "Grounds"]] it is true ?
  • Harshil Kotecha
    Harshil Kotecha about 7 years
    let dict = stringDictionaries[0] print(dict["Section"]) check this it's not work in your output result
  • John Dough
    John Dough about 7 years
    @rmaddy thanks for staying alert - updated the example to not split into sub-dictionaries. Cheers!
  • rmaddy
    rmaddy about 7 years
    Yep, that works. You can't use map on a dictionary to get a new dictionary.
  • Nasser Munshi
    Nasser Munshi about 7 years
    I've edited my code. So now you can check the output.