如何将字符串类型的数组转换成数组在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",
"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))

最新更新