Created
November 1, 2017 04:57
-
-
Save karwa/10d517815319610a7dbfa1bfb3be7f10 to your computer and use it in GitHub Desktop.
codable-nscoding bridge
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
import Foundation | |
/// This isn't safe to use before Swift gets ABI stability, because generic classes | |
/// could change their names. Also, be sure to register bridges with the Obj-C runtime | |
/// if using to decode during iOS state restoration. | |
/// | |
class CodableBridge<Wrapped: Codable>: NSObject, NSSecureCoding { | |
let value: Wrapped | |
init(_ value: Wrapped) { self.value = value } | |
static var supportsSecureCoding: Bool { return true } | |
required init?(coder aDecoder: NSCoder) { | |
guard let data = aDecoder.decodeData() else { return nil } | |
let archiver = NSKeyedUnarchiver(forReadingWith: data) | |
guard let value = archiver.decodeDecodable(Wrapped.self, forKey: "value") else { return nil } | |
self.value = value | |
} | |
func encode(with aCoder: NSCoder) { | |
let d = NSMutableData() | |
let archiver = NSKeyedArchiver(forWritingWith: d) | |
try? archiver.encodeEncodable(value, forKey: "value") | |
archiver.finishEncoding() | |
aCoder.encode(d) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, Karl!
How to use it?