Dharini Dharini - 24 days ago 17
Swift Question

How to store Only one object from response in NSMutableArray in swift 3.0 xcode 8.2 beta?

var arrayData:NSMutableArray = []
if let arrayData = response.result.value{
print("JSON: \(arrayData)")
}


I have response like below:

JSON: {
Data = (
{
"Title" = "xyz";
"Value" = 10;
},
{
"Title" = "abc";
"Value" = 20;
}
);
Success = True;}


This code store whole response in Array instead of that I want to store only array of Data object in my
arrayData
instance

Answer

The arrayData instance you have used with if let is not your class instance property arrayData of type NSMutableArray, it remains to that block also it is not array it is dictionary if you want only array of data you need to write like.

if let dic = response.result.value as? [String: Any], let array = dic["data"] as? NSArray {
     self.arrayData = NSMutableArray(array: array)
}

In Swift it is batter if you use Swift's native Array and Dictionary instead of NSArray and NSDictionary, So if you want to use native Array then declare your arrayData as [[String:Any]] means Array of Dictionary instead of NSMutableArray and use it like this.

var arrayData = [[String:Any]]()

if let dic = response.result.value as? [String: Any], let array = dic["data"] as? [[String:Any]] {
     self.arrayData = array
}