0

I have to show string data into a tableView.

{
"success": [
    [
        "An Ad with order id 2563 at location DLF, Delhi has been approved | 20 hours before|Shashank Tiwari"
    ],
    [
        "An Ad with order id 2539 at location V3S Mall has been approved | 1 week before|Shashank Tiwari"
    ],
    [
        "An Ad with order id 2515 at location Pacific Mall has been approved | 1 week before|Shashank Tiwari"
    ],
    [
        "An Ad with order id 2500 at location Ambience Mall has been rejected | 1 week before|Shashank Tiwari"
    ],
    [
        "An Ad with order id 2499 at location Vience Mall has been approved | 1 week before|Shashank Tiwari"
    ],
    [
        "An Ad with order id 2480 at location DLF, Delhi has been approved | 2 weeks before|Shashank Tiwari"
    ]
}

So I am parsing data as like below but not able to append data in to arrData Array.

           let json = try JSON(data:data
           let result = json["success"]                                           

                 print(result)


                    for arr in result.arrayValue {

                        self.arrData.compactMap{ $0 as? NSArray}
            }
4
  • Are you trying to append data by calling compactMap? what is arrData? Commented Apr 30, 2020 at 10:07
  • arrData is var arrData = [String]() its an array variable Commented Apr 30, 2020 at 10:10
  • So what are you trying to do with compactMap? Commented Apr 30, 2020 at 10:16
  • I am trying to append data in arrData from arr Commented Apr 30, 2020 at 10:20

2 Answers 2

1

If you want to flatten the array then compactMap is the wrong API.

Use reduce

let result = json["success"]
let array = (result.arrayObject as! [[String]]).reduce([], +)
self.arrData.append(contentsOf: array)
  • arrayObject returns [Any]?, you have to downcast it to the real type [[String]]
  • reduce transforms the two-dimensional array to an one-dimensional array.
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Vadian, its working fantastic for me. Can you please elaborate it ??
(result.arrayObject as! [[String]]).reduce([], +)
0

You can to it with another way like

let result = json["success"]
if let arr = result.arrayObject as? [[String]] {
    let array = arr.map { $0.first! }
    self.arrData.append(contentsOf: array)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.