@Bit-Worker
, you can try something like this:
import Foundation
struct Person: Encodable {
let first: String
let last: String
let age: Int
var encodeAll: Bool = .random()
}
extension Person {
enum AllCodingKeys: String, CodingKey {
case first, last, age
}
enum JustNamesCodingKeys: String, CodingKey {
case first, last
}
func encode(to encoder: Encoder) throws {
if encodeAll {
var container = encoder.container(keyedBy: AllCodingKeys.self)
try container.encode(first, forKey: .first)
try container.encode(last, forKey: .last)
try container.encode(age, forKey: .age)
} else {
var container = encoder.container(keyedBy: JustNamesCodingKeys.self)
try container.encode(first, forKey: .first)
try container.encode(last, forKey: .last)
}
}
}
let mysteryKids: [Person] = [
Person(first: "Charlotte", last: "Grote", age: 11),
Person(first: "Shauna", last: "Wickle", age: 12),
Person(first: "Mildred", last: "Haversham", age: 13),
Person(first: "Linton", last: "Baxter", age: 12),
Person(first: "Jack", last: "Finch", age: 12),
Person(first: "Sonny", last: "Craven", age: 12),
]
print(mysteryKids)
do {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let json = try encoder.encode(mysteryKids)
print(String(data: json, encoding: .utf8)!)
} catch {
print(error)
}
And some sample output:
[
{
"first" : "Charlotte",
"last" : "Grote",
"age" : 11
},
{
"first" : "Shauna",
"last" : "Wickle",
"age" : 12
},
{
"first" : "Mildred",
"last" : "Haversham"
},
{
"first" : "Linton",
"last" : "Baxter"
},
{
"first" : "Jack",
"last" : "Finch",
"age" : 12
},
{
"first" : "Sonny",
"last" : "Craven",
"age" : 12
}
]
Note that I added a property to Person
to determine if all keys should be encoded or not, just for purposes of illustration. If your flag is something else, this should still be enough to get you on your way.