user2039697 user2039697 - 4 months ago 14
Swift Question

How to append an array in another array in Swift?

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)

}

Answer

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)

        }
 }
Comments