Last active
August 7, 2017 23:01
-
-
Save zwaldowski/fb699ec09e8fb77cefc0ecfb76c6f7fa to your computer and use it in GitHub Desktop.
Swift 4 Beta 5 NSKeyed{Una,A}rchiver Codable Support
This file contains hidden or 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 | |
// Stolen from https://github.com/ole/whats-new-in-swift-4/blob/master/Whats-new-in-Swift-4.playground/Pages/Encoding%20and%20decoding.xcplaygroundpage/Contents.swift#L14-L31 | |
struct Card: Codable, Equatable { | |
enum Suit: String, Codable { | |
case clubs, spades, hearts, diamonds | |
} | |
enum Rank: Int, Codable { | |
case two = 2, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace | |
} | |
var suit: Suit | |
var rank: Rank | |
static func ==(lhs: Card, rhs: Card) -> Bool { | |
return lhs.suit == rhs.suit && lhs.rank == rhs.rank | |
} | |
} | |
let hand = [ | |
Card(suit: .clubs, rank: .ace), | |
Card(suit: .hearts, rank: .queen) | |
] // => [{clubs, ace}, {hearts, queen}] | |
let a = NSKeyedArchiver() | |
try a.encodeEncodable(hand, forKey: "root") | |
let data = a.encodedData // => 499 bytes | |
let u = NSKeyedUnarchiver(forReadingWith: data) | |
let handAgain = try u.decodeDecodable(Array<Card>.self, forKey: "root") ?? [] // => [{clubs, ace}, {hearts, queen}] | |
handAgain == hand // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment