我有一个 [String : Any]
字典,其中一个值是 Int
数组类型。它看起来像这样:
"file_name" : "anImage.png"
"type" : "2"
"data_bytes" : "[-119,80,78,71,13,10,26,10,0,13,73,72,68,82,0,0,2,0,2,0,8,6,-12,120,-4]"
现在我正在尝试将键 data_bytes
的值作为整数数组获取,但编译器说我无法将 String
转换为 Array
或其他东西。我尝试了以下代码:
dictionary["data_bytes"] as? [Int] //Failed
dictionary["data_bytes"] as? [NSNumber] //Failed
dictionary["data_bytes"] as? Array //Failed
dictionary["data_bytes"] as? [Int8] //Failed
dictionary["data_bytes"] as? String //Success
我还尝试遍历字符串中的所有字符:
(dictionary["data_bytes"] as? String).flatMap( Int($0) ?? 0 ) //Failed
但它给出了异常,因为在循环时,有像 [
]
,
这样的字符是不可转换的。
我应该如何将其转换为整数数组?
最佳答案
这是一个json字符串
if let str = dictionary["data_bytes"] as? String {
do {
let res = try JSONDecoder().decode([Int].self,from:Data(str.utf8))
print(res)
}
catch {
print(error)
}
}
关于ios - 如何将字符串中的整数数组转换为字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55745069/