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

贾米尔

我有一本字典,[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作为键的整数数组的值,但是编译器说我不能转换StringArray其他类型。我尝试通过以下代码:

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

但是它给人例外,因为在循环时,像[ ] ,这样的字符是不可转换的。

我应该如何将其转换为整数数组?

Sh_Khan

这是一个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)
     } 

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章