繁体   English   中英

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

[英]How to convert string type array into array in swift?

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

我想要像数组这样的解决方案: ["1","1","1","1","1","1","1"]

解决方案1:

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

解决方案2:

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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM