Search code examples
arraysswiftvariables

Remove optional for [String : Any] dictionary keys


I have an dictionary like this:

[
    "Optional(Optional(\"Optional(Optional(\\\"Optional(Optional(\\\\\\\"Optional(Optional(257))\\\\\\\"))\\\"))\"))": "Seçenek 2",
    "Optional(Optional(\"Optional(Optional(\\\"Optional(Optional(\\\\\\\"Optional(Optional(261))\\\\\\\"))\\\"))\"))": "55"
]

How remove "Optional" for all keys and use Int values like this:

["57": "Seçenek 2", "61": "55"]

Solution

  • It is awkward to me answer this question, the below code will provides the your requirement

    var dictionary = [
        "Optional(Optional(\"Optional(Optional(\\\"Optional(Optional(\\\\\\\"Optional(Optional(257))\\\\\\\"))\\\"))\"))": "Seçenek 2",
        "Optional(Optional(\"Optional(Optional(\\\"Optional(Optional(\\\\\\\"Optional(Optional(261))\\\\\\\"))\\\"))\"))": "55"
    ]
    
    for (key, value) in dictionary{
        let lKey = key.replacingOccurrences(of: "Optional(", with: "").replacingOccurrences(of: "\"", with: "").replacingOccurrences(of: ")", with: "").replacingOccurrences(of: "\\", with: "")
        dictionary.removeValue(forKey: key)
        dictionary[lKey] = value
    }
    
    print(dictionary)
    //Output: ["261": "55", "257": "Seçenek 2"]
    

    Suggention

    I suggest you to handle the key value before creating your dictionary. User if let to unwrap the key and then add key value pair to your dictionary