0

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

1 Answer 1

2

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.