I've got a class which conforms to Decodable protocol (fetching data from API) and I would like to save it in the Realm database. Problem occurs when one of my properties is array (List). It says Cannot automatically synthesize Decodable because List<Item> does not conform to Decodable
What is the best way to bypass this problem? Realm only supports arrays of primitive types.
here is my class:
class PartValue: Object, Decodable {
@objc dynamic var idetifier: Int = 0
let items = List<Item>()
}
Using the long awaited conditional conformances implemented in Swift 4.1, you can simply declare
List
to conform toDecodable
in case itsElement
conforms toDecodable
.To make this work for your specific case, you need to make sure that
Item
also conforms toDecodable
.If you also need
Encodable
conformance, simply extendList
to support that as well.Dávid's solution didn't work for me completely. I had to tweak the solution instead by replacing
decoder.unkeyedContainer()
todecoder.singleValueContainer()
, below is the solution.