ios - 如何将字符串中的整数数组转换为字符串数组?

标签 ios arrays swift dictionary

我有一个 [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/

相关文章:

ios - 通过json将图像发送到服务器

ios - 谁能帮我知道我的应用程序是否可以进入 App Store?

ios - 如何在 ViewController 中获取委托(delegate)方法以查看 *recorder 何时完成(不同的类)

Swift 如何按字节值而不是按字母顺序对字典键进行排序?

ios - 以编程方式编辑通讯簿的名字和姓氏

java - ArrayException越界

arrays - 派生类型访问时间与数组访问时间

Javascript/AJAX - 从表单获取参数数组

ios - InputStream.read 有时会停止读取

ios - 类型 `Int` 的不可变值只有名为 adjust 的可变成员