Decoding optional List of objects in RealmSwift class - swift

I am trying initialize Codable List of objects in Realm class, the problem is that the app crashes when server return empty list
this is the code for initializing List
class TicketDetails: Object, Decodable {
var working: [WorkingHour]?
var workingHours = List<WorkingHour>()
public convenience required init(from decoder: Decoder) throws {
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
if let workingArray = try container.decodeIfPresent(Array<WorkingHour>.self, forKey: .working) {
working = workingArray
workingHours.append(objectsIn: workingArray)
} else {
working = nil
workingHours = List.init()
}
}
}

A few oddities here.
TicketDetails is declared as a Realm object, but includes an array, which is just a duplicate of a Realm List property. Why? Remove the array. List needs to be a let, and remove the entire else clause as that won't work.
class TicketDetails: Object, Decodable
{
let workingHours = List<WorkingHour>()
public convenience required init(from decoder: Decoder) throws {
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
if let workingArray = try container.decodeIfPresent(Array<WorkingHour>.self, forKey: .working)
{
workingHours.append(objectsIn: workingArray)
}
}
}

It's more convenient and working solutions with the latest version of RealmCocoa 4.4.1. Don't forget define CodingKeys enum if network responses different than your models.
class TicketDetails: Object, Decodable {
var working = List<[WorkingHour]>()
var workingHours = List<WorkingHour>()
public convenience required init(from decoder: Decoder) throws {
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
self.working = try container.decodeIfPresent(List<WorkingHour>.self, forKey: .working) ?? List<WorkingHour>.self
self.workingHours = try container.decodeIfPresent(List<WorkingHour>.self, forKey: .working) ?? List<WorkingHour>.self
}
}

Related

Swift Decodable: Inject value in nested generic property

I have this API response structure (from Strapi v4):
{
"data": [
{
"id": 1,
"attributes": {
"description": "test",
}
}
]
}
I have this generic code to handle API responses and to inject the ID to my child object:
struct StrapiArrayResponse<Content: StrapiDataObjectContent>: Codable {
var data: [StrapiDataObject<Content>]
}
struct StrapiDataObject<Content: StrapiDataObjectContent>: Codable {
let id: Int
var attributes: Content
init(from decoder: Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(Int.self, forKey: .id)
self.attributes = try container.decode(Content.self, forKey: .attributes)
self.attributes.id = id
}
}
protocol StrapiDataObjectContent: Codable {
var id: Int! { get set } // I don't want this to be an Optional
}
I want my id to be a let instead of an optional var.
Is there a better way to inject the ID to my child objects (StrapiDataObjectContent)?
Here is a solution for the problem but it isn't so straightforward and requires some work.
Since you want id to be a constant we need a way to initialise Content with it so one way then is to add an init to the protocol.
protocol StrapiDataObjectContent: Codable {
var id: Int { get } //also removed 'set'
init(id: Int, copy: Self)
}
As you see this init takes an already existing object as parameter so this is kind of a copy method
So an implementation (based on the json in the question) could then be
init(id: Int, copy: Test) {
self.id = id
self.description = copy.description
}
We then need to change init(from:) in StrapiDataObject to
init(from decoder: Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(Int.self, forKey: .id)
let attributes = try container.decode(Content.self, forKey: .attributes)
self.attributes = Content(id: id, copy: attributes)
}
Now this compiles but we will get a runtime error since id is expected by the decoder for Content but doesn't exists in the json.
So this leads to the major drawback of this solution, every type conforming to StrapiDataObjectContent needs to implement a custom init(from:) just to avoid decoding the id property
To demonstrate here is a full example (based on the json in the question)
struct Test: StrapiDataObjectContent {
let id: Int
let description: String
init(from decoder: Decoder) throws {
id = 0
let container = try decoder.container(keyedBy: CodingKeys.self)
description = try container.decode(String.self, forKey: .description)
}
init(id: Int, copy: Test) {
self.id = id
self.description = copy.description
}
}

Using Decodable with injected properties

Is there any way to use Decodable with injected property?
final class Score: Decodable {
let value: Int?
let uniqueId: String
convenience init(from decoder: Decoder/*, uniqueId: String*/) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
try container.decodeIfPresent(Int.self, forKey: .value).flatMap { value = $0 }
// self.uniqueId = uniqueId
[... other properties parsing ...]
}
}
Example call:
final class Exam {
let identifier: Int
let scores: [Score]
convenience init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
identifier = try container.decode(Int.self, forKey: .identifier)
scores = try container.decode([Score].self, forKey: .scores)
// I need to pass Exam's identifier to `score` on init, because it will generate Score's `uniqueId `
[... other properties parsing ...]
}
}
That would end with error with missing uniqueId, which I need to have after init but it's not in the JSON. Since it's identifier, making it optional and setting outside is not a proper way to handle it.
I'd love to inject it the way it's commented above, but how to do it?
There is no way to extend the initialiser because it's being called indirectly and there is no API provided to extend it. Thus, there are several ways to bypass it:
BEST: Inject the value into Decoder's userInfo if possible.
Create separate class for Response and separate for model. Example below.
Use plain JSONSerialization instead of Decodable.
As #JoakimDanielson suggested, create random identifier inside default initialiser. The issue is that it's not reproducable, so in case you're saving it to the DB, you'll always override the data, since the ID with each parsing would be different.
Example for approach 2:
final class ScoreResponse: Decodable {
let value: Int?
convenience init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
try container.decodeIfPresent(Int.self, forKey: .value).flatMap { value = $0 }
[... other properties parsing ...]
}
}
final class Score {
let value: Int?
let uniqueId: String
convenience init(from response: ScoreResponse, uniqueId: String) {
self.value = response.value // etc with other properties
self.uniqueId = uniqueId
}
}
final class Exam: Decodable {
let identifier: String
let scores: [Score] = []
convenience init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
identifier = try container.decode(String.self, forKey: .identifier)
try container.decodeIfPresent([ScoreResponse].self, forKey: .scores).forEach {
scores.append({ Score(from: $0, uniqueId: identifier) })
}
}

Im trying to save custom data to cloud firestore in swiftUI, Im trying to construct the data i get from snapshot listener

The call document.data(as: ) requires Decodable protocol, it saves the data just fine as the call to addDocument(from:) requires encodable object so I pass my custom class object, yet I don't know why the other way around requires the protocol.
How do I pass the protocol?
Here is my custom class definition :
class PersonalInfo: Codable, ObservableObject {
#Published var name: String
#Published var age: Int
#Published var Sex: String
enum CodingKeys: CodingKey{
case name, age, Sex
}
init(name: String, age:Int, Sex:String) {
self.name = name
self.age = age
self.Sex = Sex
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
age = try container.decode(Int.self, forKey: .age)
Sex = try container.decode(String.self, forKey: .Sex)
}
public func encode( to encoder: Encoder) throws{
var container = try encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(age, forKey: .age)
try container.encode(Sex, forKey: .Sex)
}
}
Here is the function I am trying to construct the data after getting set of data:
mutating func loadData(){
let listener = query?.addSnapshotListener{ (snapShot, error ) in
guard let snapshot = snapShot else {
print("Error listening")
return
}
let userCollection = try? snapshot.documents.map{ document -> PersonalInfo in
let decoder = JSONDecoder()
if let user = try document.data(as: PersonalInfo(from: decoder)){
return user
}
else{
fatalError("unable to initialize type")
}
}
}
}
There is no need to create a class for your data structure. A Class: ObservableObject accepts, processes, and passes (published) needed data(values) to your View according to your data structure...
A good news: Firebase supports the Swift Codable Protocol – check this link

Decoding swift inheritance data

I have a Process class that has a Step type parameter (Step is "abstract"). I have two Step type classes: StepSign and StepReview, as shown in the code:
class Process: Codable {
let steps: Array<Step>
let actualStep: Step
private enum CodingKeys: String, CodingKey {
case steps, actualStep
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
steps = try container.decode(Array<Step>.self, forKey: .steps)
actualStep = try container.decode(Step.self, forKey: .actualStep)
}
}
class Step: Codable {
var id : Int?
}
class StepSign : Step {
var name : String?
private enum CodingKeys: String, CodingKey {
case name
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
try super.init(from: decoder)
}
}
class StepReview: Step {
var isReview: Bool
private enum CodingKeys: String, CodingKey {
case isReview
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
isReview = try container.decode(Bool.self, forKey: .isReview)
try super.init(from: decoder)
}
When I try to decode I get the Step, but I would like it to return either StepSign or StepReview. But I don't know how to indicate what type it is since at the time of decoding I don't know.
The problem I have is in the following lines:
steps = try container.decode(Array<Step>.self, forKey: .steps)
actualStep = try container.decode(Step.self, forKey: .actualStep)
Any ideas?

How to implement Codable in a custom subclass (Swift 4) [duplicate]

Should the use of class inheritance break the Decodability of class. For example, the following code
class Server : Codable {
var id : Int?
}
class Development : Server {
var name : String?
var userId : Int?
}
var json = "{\"id\" : 1,\"name\" : \"Large Building Development\"}"
let jsonDecoder = JSONDecoder()
let item = try jsonDecoder.decode(Development.self, from:json.data(using: .utf8)!) as Development
print(item.id ?? "id is nil")
print(item.name ?? "name is nil") here
output is:
1
name is nil
Now if I reverse this, name decodes but id does not.
class Server {
var id : Int?
}
class Development : Server, Codable {
var name : String?
var userId : Int?
}
var json = "{\"id\" : 1,\"name\" : \"Large Building Development\"}"
let jsonDecoder = JSONDecoder()
let item = try jsonDecoder.decode(Development.self, from:json.data(using: .utf8)!) as Development
print(item.id ?? "id is nil")
print(item.name ?? "name is nil")
output is:
id is nil
Large Building Development
And you can't express Codable in both classes.
I believe in the case of inheritance you must implement Coding yourself. That is, you must specify CodingKeys and implement init(from:) and encode(to:) in both superclass and subclass. Per the WWDC video (around 49:28, pictured below), you must call super with the super encoder/decoder.
required init(from decoder: Decoder) throws {
// Get our container for this subclass' coding keys
let container = try decoder.container(keyedBy: CodingKeys.self)
myVar = try container.decode(MyType.self, forKey: .myVar)
// otherVar = ...
// Get superDecoder for superclass and call super.init(from:) with it
let superDecoder = try container.superDecoder()
try super.init(from: superDecoder)
}
The video seems to stop short of showing the encoding side (but it's container.superEncoder() for the encode(to:) side) but it works in much the same way in your encode(to:) implementation. I can confirm this works in this simple case (see playground code below).
I'm still struggling with some odd behavior myself with a much more complex model I'm converting from NSCoding, which has lots of newly-nested types (including struct and enum) that's exhibiting this unexpected nil behavior and "shouldn't be". Just be aware there may be edge cases that involve nested types.
Edit: Nested types seem to work fine in my test playground; I now suspect something wrong with self-referencing classes (think children of tree nodes) with a collection of itself that also contains instances of that class' various subclasses. A test of a simple self-referencing class decodes fine (that is, no subclasses) so I'm now focusing my efforts on why the subclasses case fails.
Update June 25 '17: I ended up filing a bug with Apple about this. rdar://32911973 - Unfortunately an encode/decode cycle of an array of Superclass that contains Subclass: Superclass elements will result in all elements in the array being decoded as Superclass (the subclass' init(from:) is never called, resulting in data loss or worse).
//: Fully-Implemented Inheritance
class FullSuper: Codable {
var id: UUID?
init() {}
private enum CodingKeys: String, CodingKey { case id }
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(UUID.self, forKey: .id)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
}
}
class FullSub: FullSuper {
var string: String?
private enum CodingKeys: String, CodingKey { case string }
override init() { super.init() }
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let superdecoder = try container.superDecoder()
try super.init(from: superdecoder)
string = try container.decode(String.self, forKey: .string)
}
override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(string, forKey: .string)
let superencoder = container.superEncoder()
try super.encode(to: superencoder)
}
}
let fullSub = FullSub()
fullSub.id = UUID()
fullSub.string = "FullSub"
let fullEncoder = PropertyListEncoder()
let fullData = try fullEncoder.encode(fullSub)
let fullDecoder = PropertyListDecoder()
let fullSubDecoded: FullSub = try fullDecoder.decode(FullSub.self, from: fullData)
Both the super- and subclass properties are restored in fullSubDecoded.
Found This Link - Go down to inheritance section
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(employeeID, forKey: .employeeID)
}
For Decoding I did this:
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let values = try decoder.container(keyedBy: CodingKeys.self)
total = try values.decode(Int.self, forKey: .total)
}
private enum CodingKeys: String, CodingKey
{
case total
}
🚀 Swift introduced Property Wrappers in 5.1 I implemented a library called SerializedSwift that uses the power of property wrappers to Decode and Encode JSON data to objects.
One of my main goals was, to make inherited object to decode out of the box, without additonal init(from decoder: Decoder) overrides.
import SerializedSwift
class User: Serializable {
#Serialized
var name: String
#Serialized("globalId")
var id: String?
#Serialized(alternateKey: "mobileNumber")
var phoneNumber: String?
#Serialized(default: 0)
var score: Int
required init() {}
}
// Inherited object
class PowerUser: User {
#Serialized
var powerName: String?
#Serialized(default: 0)
var credit: Int
}
It also supports custom coding keys, alternate keys, default values, custom transformation classes and many more features to be included in the future.
Available on GitHub (SerializedSwift).
I was able to make it work by making my base class and subclasses conform to Decodable instead of Codable. If I used Codable it would crash in odd ways, such as getting a EXC_BAD_ACCESS when accessing a field of the subclass, yet the debugger could display all the subclass values with no problem.
Additionally, passing the superDecoder to the base class in super.init() didn't work. I just passed the decoder from the subclass to the base class.
How about using the following way?
protocol Parent: Codable {
var inheritedProp: Int? {get set}
}
struct Child: Parent {
var inheritedProp: Int?
var title: String?
enum CodingKeys: String, CodingKey {
case inheritedProp = "inherited_prop"
case title = "short_title"
}
}
Additional info on composition: http://mikebuss.com/2016/01/10/interfaces-vs-inheritance/
Here is a library TypePreservingCodingAdapter to do just that (can be installed with Cocoapods or SwiftPackageManager).
The code below compiles and works just fine with Swift 4.2. Unfortunately for every subclass you'll need to implement encoding and decoding of properties on your own.
import TypePreservingCodingAdapter
import Foundation
// redeclared your types with initializers
class Server: Codable {
var id: Int?
init(id: Int?) {
self.id = id
}
}
class Development: Server {
var name: String?
var userId: Int?
private enum CodingKeys: String, CodingKey {
case name
case userId
}
init(id: Int?, name: String?, userId: Int?) {
self.name = name
self.userId = userId
super.init(id: id)
}
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decodeIfPresent(String.self, forKey: .name)
userId = try container.decodeIfPresent(Int.self, forKey: .userId)
}
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(userId, forKey: .userId)
}
}
// create and adapter
let adapter = TypePreservingCodingAdapter()
let encoder = JSONEncoder()
let decoder = JSONDecoder()
// inject it into encoder and decoder
encoder.userInfo[.typePreservingAdapter] = adapter
decoder.userInfo[.typePreservingAdapter] = adapter
// register your types with adapter
adapter.register(type: Server.self).register(type: Development.self)
let server = Server(id: 1)
let development = Development(id: 2, name: "dev", userId: 42)
let servers: [Server] = [server, development]
// wrap specific object with Wrap helper object
let data = try! encoder.encode(servers.map { Wrap(wrapped: $0) })
// decode object back and unwrap them force casting to a common ancestor type
let decodedServers = try! decoder.decode([Wrap].self, from: data).map { $0.wrapped as! Server }
// check that decoded object are of correct types
print(decodedServers.first is Server) // prints true
print(decodedServers.last is Development) // prints true
Swift 5
The compiler synthesises decodable code only for a type that directly adopts Codable protocol so that you observe decoding for a single of your type in inheritance.
But you can try next generic approach with KeyValueCoding package (https://github.com/ikhvorost/KeyValueCoding) and this package provides access to all properties metadata and allows to get/set any property for pure swift types dynamically. The idea is to make a base Coding class which adopts KeyValueCoding and implements decoding of all available properties in init(from: Decoder):
class Coding: KeyValueCoding, Decodable {
typealias DecodeFunc = (KeyedDecodingContainer<_CodingKey>, _CodingKey) throws -> Any?
struct _CodingKey: CodingKey {
let stringValue: String
let intValue: Int?
init(stringValue: String) {
self.stringValue = stringValue
self.intValue = Int(stringValue)
}
init(intValue: Int) {
self.stringValue = "\(intValue)"
self.intValue = intValue
}
}
static func decodeType<T: Decodable>(_: T.Type) -> (type: T.Type, f: DecodeFunc) {
(T.self, { try $0.decode(T.self, forKey: $1) })
}
static var decodeTypes: [(Any.Type, DecodeFunc)] = [
decodeType(Int.self),
decodeType(Int?.self),
decodeType(String.self),
decodeType(String?.self),
// Other types to support...
]
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: _CodingKey.self)
try container.allKeys.forEach { codingKey in
let key = codingKey.stringValue
guard let property = (properties.first { $0.name == key }),
let item = (Self.decodeTypes.first { property.type == $0.0 })
else {
return
}
var this = self
this[key] = try item.1(container, codingKey)
}
}
}
It is important to provide all supported types to decode in decodeTypes variable.
How to use:
class Server: Coding {
var id: Int?
}
class Development : Server {
var name: String = ""
}
class User: Development {
var userId: Int = 0
}
func decode() {
let json = "{\"id\": 1, \"name\": \"Large Building Development\", \"userId\": 123}"
do {
let user = try JSONDecoder().decode(User.self, from:json.data(using: .utf8)!)
print(user.id, user.name, user.userId) // Optional(1) Large Building Development 123
}
catch {
print(error.localizedDescription)
}
}