Rob
Rob

Reputation: 164

How to store multiple datas in an Array in swift 4?

I am getting a JSON from an API. So, I want to store a particular value with key SKU. So, what I did was:

    var skuArr = [""]
{ (response, error) in

            if (error != nil)
            {
                print("Error \(error.debugDescription)")
            }

            else
            {
                self.coinsArr = response.arrayObject as? Array<Dictionary<String, Any>>

                for i in 0 ..<  (self.coinsArr?.count)!
                {
                    self.skuArr = [response[i]["sku"].rawValue as! String]
                }
}

So, with this I am getting the array in skuArr, but when i is 0 I am getting ["a"], and when i is 1 I want it to be ["a","b"], but it gives ["b"] only and when the loop ends with only the last value and not with ["a","b","c","d"] which I want as the final result. How can I insert each of them in the Array?

Upvotes: 0

Views: 420

Answers (2)

vadian
vadian

Reputation: 285064

First of all declare skuArr as empty string array.

var skuArr = [String]()

And this is Swift. There are better ways than ugly index based loops to extract data for example with map or compactMap

if let result = response.arrayObject as? Array<Dictionary<String, Any>> {
    self.coinsArr = result
    self.skuArr = result.compactMap{ $0["sku"] as? String }
}

And why is coinsArr declared as optional as you are going to force unwrap it anyway? It's highly recommended to use non-optional types as much as possible. Non-optionals can never cause a well-liked unexpected found nil crash

Upvotes: 1

Arnab
Arnab

Reputation: 4356

Don't use this:

self.skuArr = [response[i]["sku"].rawValue as! String]

As this will replace the previous value with new one.

Use .append to insert into array.

self.skuArr.append([response[i]["sku"].rawValue as! String])

EDIT

change your initialisation as below:

skuArr: [String] = []

Upvotes: 0

Related Questions