1

I want to get status and message from these array. I don't know how to map.

[<null>, {
    message = "Not matched";
    status = 400;
}]

This is my code

class QRScanValidAPIMapper: NSObject {
    var message: String!
    var status: Int!

    init(_ rawData: Any) {
        print(rawData)
        let data = rawData as? Dictionary<String,Any>
        self.message = data?["message"] == nil ? rawData as! String : data?["message"] as! String
        self.status = data?["status"] == nil ? 0 : data?["status"] as! Int
    }
}
9
  • 1
    Is the first part of your question what print(rawData) prints? so you have a null first element in the array ? Commented Apr 1, 2019 at 4:20
  • let mappedResponse = QRScanValidAPIMapper(data) i added the data. @u.gen Commented Apr 1, 2019 at 4:24
  • Are you sure { message = "Not matched"; status = 400; } is identical dictionary in that Array ? Commented Apr 1, 2019 at 4:25
  • 1
    If rawData is an array as what you seem to be showing, your cast to Dictionary<String,Any> will always fail. Commented Apr 1, 2019 at 4:26
  • 1
    Ok let me fix this. I hope that Array will be same as you describe for all failure scenario. Commented Apr 1, 2019 at 4:30

1 Answer 1

1

Get the failure dictionary from Array and get the value from it. like this -

let array = [nil, ["message" : "Not matched", "status" : 400]]

for response in array {

        if let failureResponse = response {

            print(failureResponse["message"]!)
            print(failureResponse["status"]!)
        }
}

Let me know whether you are still having any issue.

Sign up to request clarification or add additional context in comments.

5 Comments

I got this error in line 6 Initializer for conditional binding must have Optional type, not 'Any'
@RedHeart Can you add line 6 ?
for response in array {} this line -
@RedHeart what is array data type?
if let failureResponse = array as? [String: Any] {} i need to add this code ` as? [String: Any] {}` Thanks bro

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.