How to append an array in another array in Swift? - arrays

I have a JSON response whose answer I have to parse. I write the single elements into an array called courseDataArray using a for loop. After that, I want to write this newly created array into another array called combinedCourseArray with the aim to pass that on to a UITableView. Creating the first array seems to work fine.
But how can I create another array combinedCourseArray who contain all arrays of type courseDataArray?
for (index, element) in result.enumerate() {
// get one entry from the result array
if let courseEntry = result[index] as? [String:AnyObject]{
//work with the content of the array
let courseName = courseEntry["name"]
let courseType = courseEntry["course_type"]
let courseDate = courseEntry["cor_date"]
let courseId = courseEntry["cor_id"]
let duration = courseEntry["duration"]
let schoolId = courseEntry["sco_id"]
let status = courseEntry["status"]
let courseDataArray = ["courseName" : courseName, "courseType": courseType, "courseDate": courseDate, "courseId": courseId, "duration": duration, "schoolId":schoolId, "status":status]
print(courseDataArray)
var combinedCourseArray: [String: AnyObject] = [:]
combinedCourseArray[0] = courseDataArray //does not work -- error: cannot subscript a value of type...
// self.shareData.courseStore.append(scooter)
}

You should move the combinedCourseArray declaration outside of the array. It should be var combinedCourseArray: [[String: AnyObject]] = [[:]] since it's an array and not a dictionary.
And you should be doing
combinedCourseArray.append(courseDataArray)
instead of
combinedCourseArray[0] = courseDataArray

var FirstArray = [String]()
var SecondArray = [String:AnyObject]()
FirstArray.append(contentsOf: SecondArray.value(forKey: "key") as! [String])

First declare this combinedCourseArray array out side this loop
var combinedCourseArray: [[String: AnyObject]] = [[String: AnyObject]]()
for (index, element) in result.enumerate() {
// get one entry from the result array
if let courseEntry = result[index] as? [String:AnyObject]{
//work with the content of the array
let courseName = courseEntry["name"]
let courseType = courseEntry["course_type"]
let courseDate = courseEntry["cor_date"]
let courseId = courseEntry["cor_id"]
let duration = courseEntry["duration"]
let schoolId = courseEntry["sco_id"]
let status = courseEntry["status"]
let courseDataArray = ["courseName" : courseName, "courseType": courseType, "courseDate": courseDate, "courseId": courseId, "duration": duration, "schoolId":schoolId, "status":status]
print(courseDataArray)
combinedCourseArray.append(courseDataArray) //does not work -- error: cannot subscript a value of type...
// self.shareData.courseStore.append(scooter)
}
}

Just use flatMap on the outer array to translate one array into another array, possibly dropping some elements:
let courseDataArray : [[String:AnyObject?]] = result.flatMap {
guard let courseEntry = $0 as? [String:AnyObject] else {
return nil
}
return [
"courseName" : courseEntry["name"],
"courseType": courseEntry["course_type"],
"courseDate": courseEntry["cor_date"],
"courseId": courseEntry["cor_id"],
"duration": courseEntry["duration"],
"schoolId": courseEntry["sco_id"],
"status": courseEntry["status"]
]
}
Of course, the guard isn't really necessary since the input type is presumably already [[String:AnyObject]] and since you then can't have any internal failures, you can just use map instead of flatMap

Related

How to filter Dictionary of Array Swift3.0?

I've an Dictionary which contains Array and that Array has another Dictionary ant it also has another array. How do I get the last array by using 'Dictionary.Filter'.
For Example
Dict1->Array1->Dict2->Array2.
Here I need
Array2
I want to get "DeviceLsit" Array
Check this out! Based on your screenshot, I have managed to achieve it!
func filterArray() {
let dictPlist = Dictionary<String, Any>()
if let arrKeyName = dictPlist["key"] as? Array<Dictionary<String, Any>> {
let yourSecondArray = arrKeyName.filter({ (keyDict) -> Bool in
guard let _ = keyDict["keyName"] as? Array<Any> else {
return false
}
return true
})
}
}
Hope this helps!
if you want array of DeviceLists you can got through categories and get device lists
let root: [String: Any] = ["Categories": [ ["deviceList": ["1","2","3","4"]], ["deviceList": ["5","6","7","8"]] ]]
if let categories = root["Categories"] as? [Any] {
var deviceLists: [String] = []
for cat in categories {
if let cat = cat as? [String: Any], let deviceNames = cat["deviceList"] as? [String] {
deviceLists.append(contentsOf: deviceNames)
}
}
print(deviceLists)
}
here is the short anser :
Assume that your desired Array has Any Type. you can make it as you want like String , Int etc...!
let dict = [String:[[String:[Any]]]]()
let arr = dict.flatMap({($0.value).flatMap({($0.values)})}).last
print(arr) <-- your desired Array

How to get an element of an array inside another array?

So the only way i can think of achieving this is by putting the array inside mainArray into a variable and then indexing that. Is there an easier way?
mainArray = [ 3400, "Overwatch", [UIButton(), UIButton()]] // Some buttons already made
currentButtonArray = mainArray[mainArray.count - 1] as! NSArray
for i in 0..<currentButtonArray.count {
buttonArray.append( currentButtonArray[i] as! UIButton)
}
If there is one array containing only UIButton instances, just filter it.
let mainArray : [Any] = [3400, "Overwatch", [UIButton(), UIButton()]]
if let buttonArray = mainArray.filter({$0 is [UIButton]}).first as? [UIButton] {
print(buttonArray)
}
or
let buttonArray = Array(mainArray.flatMap{$0 as? [UIButton]}.joined())
The second approach returns a non-optional empty array if there is no array of UIButton in mainArray
If the subarray is of all one type, you can append all in one go:
var buttonArray = [UIButton]()
let mainArray:[Any] = [3400, "Overwatch", [UIButton(), UIButton()]] // Some buttons already made
if let currentButtonArray = mainArray.last as? [UIButton] {
buttonArray.append(contentsOf: currentButtonArray)
}
Or you could simply write:
guard let currentButtonArray = mainArray.last as? [UIButton] else {
// do something e.g. return or break
fatalError()
}
// do stuff with array e.g. currentButtonArray.count
If you didn't know the position in the array of the nested UIButton array or if there were multiple nested button arrays then this would work:
let buttonArray = mainArray.reduce([UIButton]()){ (array, element) in if let bArray = element as? [UIButton] {
return array + bArray
}
else {
return array
}
}
Note: this is Swift 3 code.

How to update swift dictionary value

I rewrite this code from php. And I find it difficult to make it work in swift.
var arrayOfData = [AnyObject]()
for index in 1...5 {
var dict = [String: AnyObject]()
dict["data"] = [1,2,3]
dict["count"] = 0
arrayOfData.append(dict)
}
for d in arrayOfData {
let data = d as AnyObject
// I want to update the "count" value
// data["count"] = 8
print(data);
break;
}
Presumably, you want to update the value inside of arrayOfData when you assign data["count"] = 8. If you switch to using NSMutableArray and NSMutableDictionary, then your code will work as you want. The reason this works is that these types are reference types (instead of value types like Swift arrays and dictionaries), so when you're working with them, you are referencing the values inside of them instead of making a copy.
var arrayOfData = NSMutableArray()
for index in 1...5 {
var dict = NSMutableDictionary()
dict["data"] = [1,2,3]
dict["count"] = 0
arrayOfData.addObject(dict)
}
for d in arrayOfData {
let data = d as! NSMutableDictionary
data["count"] = 8
print(data)
break
}
Assuming your array has to be of form '[AnyObject]' then something like this:
var arrayOfData = [AnyObject]()
for index in 1...5 {
var dict = [String: AnyObject]()
dict["data"] = [1,2,3]
dict["count"] = 0
arrayOfData.append(dict)
}
for d in arrayOfData {
// check d is a dictionary, else continue to the next
guard let data = d as? [String: AnyObject] else { continue }
data["count"] = 8
}
But preferably your array would be typed as an array of dictionaries:
var arrayOfData = [[String: AnyObject]]()
for index in 1...5 {
var dict = [String: AnyObject]()
dict["data"] = [1,2,3]
dict["count"] = 0
arrayOfData.append(dict)
}
for d in arrayOfData {
// swift knows that d is of type [String: AnyObject] already
d["count"] = 8
}
EDIT:
So the issue is that when you modify in the loop, you're creating a new version of the dictionary from the array and need to transfer it back. Try using a map:
arrayOfData = arrayOfData.map{ originalDict in
var newDict = originalDict
newDict["count"] = 8
return newDict
}
The most efficient way would be to find the index of the relevant values entry, and then replace that entry. The index is essentially just a pointer into the hash table, so it's better than looking up by key twice:
To update all the entries, you can loop through the indices one at a time:
for i in dictionary.values.indices {
dictionary.values[i].property = ...
}
To update a particular key, use:
let indexToUpdate = dictionary.values.index(forKey: "to_update")
dictionary.values[i].property = ...

How we can find an element from [AnyObject] type array in swift

I have [AnyObject] array
var updatedPos = [AnyObject]()
I am setting data in that according to my requirement like!
let para:NSMutableDictionary = NSMutableDictionary()
para.setValue(posId, forKey: "id")
para.setValue(posName, forKey: "job")
let jsonData = try! NSJSONSerialization.dataWithJSONObject(para, options: NSJSONWritingOptions())
let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String
self.updatedPos.append(jsonString)
Now in my code i have some requirement to remove the object from this array where id getting matched according to requirement Here is the code which i am trying to implement
for var i = 0; i < updatedPos.count; i++
{
let posItem = updatedPos[i]
print("Id=\(posItem)")
let pId = posItem["id"] as? String
print("secRId=\(pId)")
if removeId! == pId!
{
updatedPos.removeAtIndex(i)
}
}
Here print("Id=\(posItem)") give me output asId={"id":"51","job":"Programmer"} but here i am not able to access id from this object. here print("secRId=\(pId)") give me nil
First of all use native Swift collection types.
Second of all use types as specific as possible.
For example your [AnyObject] array can be also declared as an array of dictionaries [[String:AnyObject]]
var updatedPos = [[String:AnyObject]]()
Now create the dictionaries and add them to the array (in your example the dictionary is actually [String:String] but I keep the AnyObject values).
let para1 : [String:AnyObject] = ["id" : "51", "job" : "Programmer"]
let para2 : [String:AnyObject] = ["id" : "12", "job" : "Designer"]
updatedPos.append(para1)
updatedPos.append(para2)
If you want to remove an item by id use the filter function
let removeId = "12"
updatedPos = updatedPos.filter { $0["id"] as? String != removeId }
or alternatively
if let indexToDelete = updatedPos.indexOf{ $0["id"] as? String == removeId} {
updatedPos.removeAtIndex(indexToDelete)
}
The JSON serialization is not needed for the code you provided.
PS: Never write valueForKey: and setValue:forKey: unless you know exactly what it's doing.
After some little bit stuffs I have found the very easy and best solution for my question. And I want to do special thanks to #vadian. Because he teach me new thing here. Hey Thank you very much #vadian
Finally the answer is I had covert posItem in json Format for finding the id from Id={"id":"51","job":"Programmer"} this string
And the way is
let data = posItem.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
if let dict = json as? [String: AnyObject] {
let id = dict["id"]
if removeId! == id! as! String
{
updatedLoc.removeAtIndex(i)
}
}
}
catch {
print(error)
}

Change array back to dictionary - SWIFT

I have a for loop that creates a dictionary and then I append the dictionary to an array. I append the dictionary to an array because I don't know how to add more than one value with the same key, when I do that in the for loop the key / value pair is just updated and the old key / value pair is deleted What is the best way to change the array back to a dictionary?
import UIKit
class ViewController: UIViewController {
var jobTitle = ""
var jobDescription = ""
var dict:[String: AnyObject] = ["jobTitle": "jobTitle", "jobDescription": "jobDescription"]
var tArray = [[String: AnyObject]]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for var i = 0; i < 3; ++i {
jobTitle = "job1"
jobDescription = "Desc1"
dict["jobTitle"] = "job1"
dict["jobDescription"] = "Desc1"
tArray.append(dict)
}
println("\(tArray)")
}
}
Like such, where you have more than one value associated with each key:
let jobnames = ["j1", "j2", "j3"]
let jobdescs = ["d1", "d2", "d3"]
var dict : [String:[String]] = [:]
for index in 0..<3 {
if nil == dict["jobTitle"] { dict["jobTitle"] = [] }
if nil == dict["jobDesc" ] { dict["jobDesc" ] = [] }
dict["jobTitle"]!.append(jobnames[index])
dict["jobDesc" ]!.append(jobdescs[index])
}
Here is the output:
You call the same assignmenta such as
jobTitle = "job1"
at every iteration of the loop. Of course the variable will always contain the same value. The same is true for dict. It is an ivar, so you keep overwriting it.
What you want is to create a new collection of type [String: AnyObject] to add to your array.
let newDict:[String : AnyObject] = [titleKey : titleText,
descriptionKey : descriptionText]
tArray.append(newDict)

Resources