Skip to content

Instantly share code, notes, and snippets.

@ansonyao
Last active November 12, 2021 09:31
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ansonyao/41137bb3cbbca8ef31a13b6bc96ee422 to your computer and use it in GitHub Desktop.
Save ansonyao/41137bb3cbbca8ef31a13b6bc96ee422 to your computer and use it in GitHub Desktop.
Realm Object Extension for Codable (RealmOptional and Realm List)
//
// RealmSwift+Codable.swift
//
// Created by Anson Yao on 7/25/18.
//
//Adding this file can make your classes inherited from Realm Object comfirm to Codable easily
//Inspired by @mishagray https://gist.github.com/mishagray/3ee82a3a82f357bfbf8ff3b3d9eca5cd
import Foundation
import RealmSwift
extension RealmOptional : Encodable where Value: Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
if let v = self.value {
try v.encode(to: encoder)
} else {
try container.encodeNil()
}
}
}
extension RealmOptional : Decodable where Value: Decodable {
public convenience init(from decoder: Decoder) throws {
self.init()
let container = try decoder.singleValueContainer()
if !container.decodeNil() {
self.value = try Value(from: decoder)
}
}
}
extension List : Decodable where Element : Decodable {
public convenience init(from decoder: Decoder) throws {
self.init()
var container = try decoder.unkeyedContainer()
while !container.isAtEnd {
let element = try container.decode(Element.self)
self.append(element)
}
}
}
extension List : Encodable where Element : Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
for element in self {
try element.encode(to: container.superEncoder())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment