0

I want to add new data to Mappable class. Here is my class:

import Foundation
import ObjectMapper

struct AllcategoriesModel : Mappable {
    var allcategories : [Allcategories]?

    init?(map: Map) {

    }

    mutating func mapping(map: Map) {
        allcategories <- map["allcategories"]
    }

}

The way I am adding new data to class:

if json["allcategories"].exists() {
    categoriesDataSource   = Mapper<AllcategoriesModel>().map(JSON: json.object as! [String : Any])
    //Other Stuff...
}

Now, I want to append data manually, any help will be appreciated.

Sakshi
  • 1,060
  • 11
  • 25
Shahzad
  • 99
  • 2
  • 11

1 Answers1

1

After initialisation of AllcategoriesModel struct object categoriesDataSource, you can append data to it just like you would do in any other object.

categoriesDataSource.allcategories.append(newElement)

Also, why did you leave the init?(map: Map) empty. It should initialize the allcategories array.

allcategories = try? map.value("allcategories")

Otherwise the allcategories will remain nil and thus your append method call won't work.

UditS
  • 1,936
  • 17
  • 37
  • i dont understand your logic bro – Shahzad Jan 29 '19 at 08:25
  • After you initialize `categoriesDataSource = Mapper().map(JSON: json.object as! [String : Any])`, do you get a value in categoriesDataSource.allcategories or is it nil ? – UditS Jan 29 '19 at 08:35
  • yes i get values but after this i want to append some more data manually – Shahzad Jan 29 '19 at 11:12
  • Did you try `categoriesDataSource.allcategories.append(newElement)` ? – UditS Jan 31 '19 at 08:54
  • if another not understand this comment can adapt with this link https://stackoverflow.com/questions/47281375/convert-json-string-to-json-object-in-swift-4/47281832 you will can add data to Mappable object by jsonObject in same solution this answer – Papon Smc Jul 15 '21 at 09:12