Home > Back-end >  How can I create a more detailed array with objects | Swift
How can I create a more detailed array with objects | Swift

Time:01-13

Essentially I have been creating the following simple String/Int arrays to record info into an array set (which of course checks for duplicates before appending) how can I record an ID alongside the string to create a JSON array?

Currently doing the following:

var myArray = Set<String>()
myArray.insert("Example1")

["Example1","Example2","Example3"]

Example of what I would like to achieve.

[{"myexample":"Example2","id":1},{"myexample":"Example3","id":2}]

CodePudding user response:

You can use a struct that conforms to Codable to represent your data:

struct Model : Codable, Hashable {
    var myexample: String
    var id: Int
}

var mySet = Set([Model(myexample: "Example2", id: 1),
               Model(myexample: "Example3", id: 2)])
mySet.insert(Model(myexample: "Example4", id: 3))

do {
    let json = try JSONEncoder().encode(mySet)
    print(String(data: json, encoding: .utf8)!)
} catch {
    print(error)
}
  •  Tags:  
  • Related