如何在swift中将字符串型数组转换为数组?

我的字符串是:"[\"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"0\"]"

我想要类似数组的解决方案:["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
✅ 最佳回答:

字符串是JSON。一个简单的方法是

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