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
Alexa
  • 53
  • 1
  • 2
  • 7

4 Answers4

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.

Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
  • it's not id": nil my JSON add_user_product: will showing if values available it will show id and its value. @Dharmesh Khan – Alexa Aug 08 '18 at 06:56
  • 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 Aug 08 '18 at 06:58
  • 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. – Alexa Aug 08 '18 at 07:13
  • I have already mentioned that in my answer but you can get more info here: https://stackoverflow.com/questions/26347777/swift-how-to-remove-optional-string-character – Dharmesh Kheni Aug 08 '18 at 07:14
  • 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 – Alexa Aug 08 '18 at 07:25
  • Thats because `"add_user_product":null` and you need to replace `//print("Failure")` with `addlistIDData.append(nil)` from my answer. And Don't be sad I am here to help. :D – Dharmesh Kheni Aug 08 '18 at 07:30
  • Thanks buddy Btw I am getting output [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil] but my JSON I have two add_user_product:ID values so it should come like [10, nil, 11] Right?@Dharmesh Kheni – Alexa Aug 08 '18 at 07:37
  • Yes are you are right. Still not getting correct values? It also depends on how many values you are getting from server. – Dharmesh Kheni Aug 08 '18 at 07:54
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 {
   //
}
Deepak
  • 724
  • 4
  • 13
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.

PiyushRathi
  • 956
  • 7
  • 21
  • Wow great but I am getting error like Cannot invoke initializer for type 'Formatter' with an argument list of type '(String, Int)' @PiyushRathi – Alexa Aug 08 '18 at 06:29
  • 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 – Alexa Aug 08 '18 at 06:35
  • ohh you have taken resultArray is Int ok will update that way – PiyushRathi Aug 08 '18 at 06:36
  • 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 – Alexa Aug 08 '18 at 06:41
  • Nope, we have written let add_id = add_user_product["id"] as? Int so it will not add optional value – PiyushRathi Aug 08 '18 at 06:42
  • if let add_id = add_user_product["id"] as? Int { self.addlistIDData.append(add_id) } else { self.addlistIDData.append(0) } print(self.addlistIDData) I am getting output [Optional(190), Optional(191), Optional(192), Optional(195), Optional(193)] @piyushRathi – Alexa Aug 08 '18 at 06:46
  • if possible can you share your sample JSON? – PiyushRathi Aug 08 '18 at 06:59
  • sure will check and if needed make changes – PiyushRathi Aug 08 '18 at 07:02
  • hey @Alexa, as per your requirement array [10,nil,11,......], we need to keep code like this only. But when you try to access 'resultArray' then you have to check if it contains value or nil. – PiyushRathi Aug 08 '18 at 07:31
  • 1
    yes buddy Got it and keep on trying let you know Soon. – Alexa Aug 08 '18 at 07:43
  • Sure, keep trying :) – PiyushRathi Aug 08 '18 at 07:48
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)]
Lal Krishna
  • 15,485
  • 6
  • 64
  • 84