0

I am trying to get JSON values and appending into array. Here, below code add_user_product have a chance to come null. If it is null need to append null into array and if not null need to store ID also.

I am trying to get output like - [10,null,12,13,null,……]

 // add_user_products & If add_user_product == null need to store null otherwise add_user_product ["id"]
if let add_user_product = fields[“add_user_product"] as? [String : Any]  {

   let add_id  = add_user_product["id"] as! Int

    self.addlistIDData.append(add_id)
 }
 else {
    //print("Failure")
 }

below my sample response

{  
   "students":[  
      {  
         "grade":0,
         "add_user_product": 
            {  
               "id":10
            }
      },
      {  
         "grade":1,
         "add_user_product":null
      },
      {  
         "grade":2,
         "add_user_product": 
            {  
               "id":11
            }
      }
   ]
}

Expected output: [10,null,11,......] //This array I am going to use Tableview cell
1
  • what data will display in tableviewcell if there is no add_user_product? Commented Aug 8, 2018 at 6:59

4 Answers 4

4

I suggest use nil instead of null string.

Declare your addlistIDData type as [Int?] where Int is an Optional.

Consider below example I have created for you:

    var addlistIDData: [Int?] = [10, nil, 12, 13, nil]  //Created array just for example

    //created dict for testing purpose
    let fields: [String : Any]? = ["add_user_product": ["id": nil]]

    if let field = fields {

        if let add_user_product = field["add_user_product"] as? [String:Any] {
            let add_id  = add_user_product["id"] as? Int
            //now append your object here weather it's a nil or it has any value 
            addlistIDData.append(add_id)
        }
    }
    else {
        //print("Failure")
    }

    print(addlistIDData)

And output will be:

[Optional(10), nil, Optional(12), Optional(13), nil, nil]

PS: You need to cast an object with if let or with guard let whenever you are accessing objects from this addlistIDData array.

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

8 Comments

it's not id": nil my JSON add_user_product: will showing if values available it will show id and its value. @Dharmesh Khan
You can add values in my example instead of nil and you will see that value appended into your addlistIDData array. Give it a try in playground.
Dharmesh kheni Do you know how to remove Optionals also whenever values appending from JSON into that array Its appending [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, Optional(202)] last index not exact index.
I have already mentioned that in my answer but you can get more info here: stackoverflow.com/questions/26347777/…
I am so sad it is not working properly. See my JSON add_user_product some place null and some place giving ID value. but I am getting response all values nil from your solution buddy. Could you please check above my JSON once again. It's list of values and we need to check add_user_product null if it is null need to store it if it provide value need to store values proper series. Expecting output: [10,null,11,.......] @Dharmesh Kheni
|
2

null will not be identifiable, the only way to store it in your array would be to store it as String, But for that also you'll have to store othere elements as String.

But i would suggest instead of adding null just add 0 as:

var arr = [Int]()
if let add_user_product = fields["add_user_product"] as? [String: Any] {

       if let productId = add_user_product["id"] as? Int {
            arr.append(productId)
        } else {
            arr.append(0)
        }
} else {
   //
}

2 Comments

great @Deepak Can I change 0 to nill?
My array showing like [Optional(190), Optional(191), Optional(192), Optional(195), Optional(193)] @Deepak
1

You can do like this:

 var resultArray = [Int?]()
 if let add_user_product = fields["add_user_product"] as? [String: Any] {

        if let add_id = add_user_product["id"] as? Int {
            resultArray.append(add_id)
        } else {
            resultArray.append(nil)
        }
    } else {
        //print("Failure")
    }

Hope this Helps.

11 Comments

Wow great but I am getting error like Cannot invoke initializer for type 'Formatter' with an argument list of type '(String, Int)' @PiyushRathi
I am so sorry I am getting Cannot convert value of type 'String' to expected argument type 'Int?' because I am maintaining my array var resultArray: [Int?] = [] not String.How to fit this @PiyushRathi
ohh you have taken resultArray is Int ok will update that way
Great but I am getting output like [Optional(190), Optional(191), Optional(192), Optional(195), Optional(193)]. how to remove optionals also there no nil values. @PiyushRathi
yes buddy Got it and keep on trying let you know Soon.
|
1

You can use compactMap:

let arrayDict = [ ["id" : 3], ["id" : nil], ["id" : 5] ]
let result = arrayDict.compactMap { $0["id"] }
print(result)

Output:

[Optional(3), nil, Optional(5)]

2 Comments

I think it's very opposite my issue. I am trying to remove optionals from array also there is no nil values
what's your input array? You can remove nil from array using compactMap func

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.