Being a Swift newbie I am trying to fetch a list of JSON objects, save them to Core Data, then display in a SwiftUI List:
The JSON objects have a unique numeric uid (acting as PRIMARY KEY in my PostgreSQL backend).
I map them to id in my TopModel.swift:
struct Top: Codable, Identifiable {
var id: Int { uid }
let uid: Int
let elo: Int
let given: String
let photo: String?
let motto: String?
let avg_score: Double?
let avg_time: String?
}
Then I have a singleton DownloadManager.swift, which downloads the JSON list and stores the objects into the Core Data:
func getTopsCombine() {
guard let url = URL(string: "https://slova.de/ws/top") else { return }
URLSession.shared.dataTaskPublisher(for: url)
.subscribe(on: DispatchQueue.global(qos: .background))
.receive(on: DispatchQueue.main)
.tryMap(handleOutput)
.decode(type: TopResponse.self, decoder: JSONDecoder())
.sink{ ( completion ) in
print(completion)
} receiveValue: { [weak self] (returnedTops) in
for top in returnedTops.data {
print(top)
let topEntity = TopEntity(context: PersistenceController.shared.container.viewContext)
topEntity.uid = Int32(top.id)
topEntity.elo = Int32(top.elo)
topEntity.given = top.given
topEntity.motto = top.motto
topEntity.photo = top.photo
topEntity.avg_score = top.avg_score ?? 0.0
topEntity.avg_time = top.avg_time
}
self?.save()
}
.store(in: &cancellables)
}
Unfortunately, this results in multiple identical records being saved in the Core Data (and as you can see in the above screenshot).
What is the standard iOS solution here?
How to enforce the uniqueness (in my original Android/Room app I use @PrimaryKey public int uid; for that)? I do not see such an option in Xcode:
And how to merge fetched list of JSON objects (in my Android app I use DiffUtils)?


