Home > OS >  How to convert string type array into array in swift?
How to convert string type array into array in swift?

Time:06-08

My string is: "[\"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"0\"]"

I want solution like array: ["1","1","1","1","1","1","1"]

Solution1:

let test = "[\"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"0\"]"
let array = test.map( { String($0) })
debugPrint(array ?? []) //No use

Solution2:

var unescaped: String {
    let entities = ["\0": "\\0",
                    "\t": "\\t",
                    "\n": "\\n",
                    "\r": "\\r",
                    "\"": "\\\"",
                    "\'": "\\'",
                    "": "\"",
    ]
    
    return entities
        .reduce(self) { (string, entity) in
            string.replacingOccurrences(of: entity.value, with: entity.key)
        }
        .replacingOccurrences(of: "\\\\(?!\\\\)", with: "", options: .regularExpression)
        .replacingOccurrences(of: "\\\\", with: "\\")
}


debugPrint("[\"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"0\"]".unescaped) //No use

CodePudding user response:

The string is JSON. An easy way is

let test = "[\"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"0\"]"
let array = try! JSONDecoder().decode([String].self, from: Data(test.utf8))
  • Related