Skip to content

Instantly share code, notes, and snippets.

@vikingosegundo
Created March 26, 2022 18:15
Show Gist options
  • Save vikingosegundo/1be8104132a68915b12fbb2ae7e6ac0b to your computer and use it in GitHub Desktop.
Save vikingosegundo/1be8104132a68915b12fbb2ae7e6ac0b to your computer and use it in GitHub Desktop.
extension Stack {
struct Transcoder: Codable {
enum CodingKeys: String, CodingKey { case elements }
let stack: Stack<T>
init(stack s:Stack<T>) { stack = s }
init(from decoder: Decoder) throws {
stack = Stack(createStack(with:try decoder.container(keyedBy:CodingKeys.self).decode(Array<T>.self,forKey:.elements)))
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
var elements: [T] = []
while let x = stack.pop() { elements.append(x) }
try container.encode(elements, forKey: .elements)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment