0

I am getting the json of "files" as response and I want to store them in single Array. Since I am new in swift development, I am unable to figure out how to do this. Any helps would be really appreciated. I want them as below

let myFileArray = [file1, file2.....]
Kamran
  • 14,987
  • 4
  • 33
  • 51
Rishabh Shukla
  • 461
  • 6
  • 19
  • "doc":[{"nameChange":[{"file_type":"jpg","file":"file.jpg"},{"file_type":"jpg","file":"file2.jpg"}....... this is my response – Rishabh Shukla May 01 '18 at 10:18
  • Possible duplicate of [Array from dictionary keys in swift](https://stackoverflow.com/questions/26386093/array-from-dictionary-keys-in-swift) – rbaldwin May 01 '18 at 10:36
  • You should create appropriate objects and store them into array, try to use Codable from Swift 4 – PPL May 01 '18 at 10:47
  • @RishabhShukla Your question is not clear. What do you want in `Array` all `files` or all `filesTypes` or what else? – TheTiger May 01 '18 at 11:27

2 Answers2

0

Example:-responce is your web services data

 let data = responce as? [String:AnyObject]
 let respArr = data["doc"] as? [AnyObject]
 let responceData = respArr.first as? [String:AnyObject]
 let nameChange = responceData["nameChange"] as? as! Array<Dictionary<String, Any>>
 let strFileName = nameChange["file"] as? String
 Print("\(nameChange.count),\(strFileName)")
Himanshu Patel
  • 1,015
  • 8
  • 26
0

You can use flatMap or compactMap to do this like:

If you're using swift 4.1 use compactMap otherwise use flatMap.

// Your dictionary
let dictionary = response as? [String: Any]
// Create an empty Array
var myFileArray = [String]()
// Get the doc array
if let docs = dictionary?["doc"] as? [[String: Any]] {
    // for each doc array
    for doc in docs {
        // get the nameChange array
        if let nameChange = doc["nameChange"] as? [[String: Any]] {
            // convert the inner dictionary to string array
            let fileNameArray = nameChange.compactMap { (dictionary) -> String? in
                return dictionary["file"] as? String
            }

            // append the array into main array
            myFileArray.append(contentsOf: fileNameArray)
        }
    }
}
// Here is your final string array of filename
print(myFileArray)
Mukesh
  • 2,792
  • 15
  • 32