1

I have a dictionary of [String : Any] in which one of the value is of type array of Int. Its look something like this:

 "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]"

Now i am trying to get the value against the key data_bytes as integer array but compiler is saying that i can't cast String to Array or something other. I tried by following codes:

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

I also tried looping through all characters in string:

 (dictionary["data_bytes"] as? String).flatMap( Int($0) ?? 0 ) //Failed

But its giving exception because while looping, there are characters like [ ] , that is not convertible.

How am I supposed to convert this to array of integers?

Jamil
  • 330
  • 1
  • 6
  • 25

1 Answers1

5

This is a json string

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

}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87