Home > OS >  Swift: How to dynamically append value(s) into string of dictionary from an array of Int
Swift: How to dynamically append value(s) into string of dictionary from an array of Int

Time:06-24

Let say I have array of Int:

var intArr = [1,2,3,4]

and a string of dictionary:

var dictString = "[{\"id\": value1, {\"id\":value2,}, {\"id\":value3}, {\"id\":value4}]"

those value1,2,3,4 are Int type aswell

and I want to replace value1,2,3,4 with the value from stringArr. My expectation is something like

"[{\"id\": 1, {\"id\":2,}, {\"id\":3}, {\"id\":4}]"

Thank you!

CodePudding user response:

May be this you can achieve by one of the fowling way

Note: I'm assuming that you have below input

var intArr = [1,2,3,4]
var dictString = "[{\"id\": 0}, {\"id\":0}, {\"id\":0}, {\"id\":0}]"

Method 1: Write an extension for String

extension String {
    func getMapped(with list: [Int]) -> String? {
        guard let jsonData = self.data(using: .utf8) else {
            return nil
        }
        do{
            var counter = -1
            if let json = try JSONSerialization.jsonObject(with: jsonData) as? [[String: Int]]{
                let result = json.map { ob -> [String: Int] in
                    counter  = 1
                    return counter < list.count ? ["id" : list[counter]] : ob
                }
                return String(describing: result)
            }
        }catch let e {
            print("e \(e)")
            return nil
        }
        return nil
    }
}

Now you can call that function

print(dictString.getMapped(with: intArr))
Output: Optional("[[\"id\": 1], [\"id\": 2], [\"id\": 3], [\"id\": 4]]")

Method 2: Since I can see the id is in common for all dictionary objects, so you can simply map your intArry to convert to array of dictionary objects.

    let mapped = intArr.map({["id": $0]})
    let mappedString = String(describing: mapped)
    print(mappedString)
    Output: [["id": 1], ["id": 2], ["id": 3], ["id": 4]]
  • Related