Last active
November 12, 2021 09:31
-
-
Save ansonyao/41137bb3cbbca8ef31a13b6bc96ee422 to your computer and use it in GitHub Desktop.
Realm Object Extension for Codable (RealmOptional and Realm List)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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