Skip to content

Instantly share code, notes, and snippets.

@john-mueller
Created June 2, 2020 20:17
Show Gist options
  • Save john-mueller/cb5fe3d39afe47ad7c94a84a6670e010 to your computer and use it in GitHub Desktop.
Save john-mueller/cb5fe3d39afe47ad7c94a84a6670e010 to your computer and use it in GitHub Desktop.
Codable conformance for Swift's Character
extension Character: Codable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(String(self))
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let string = try container.decode(String.self)
guard let character = string.first else {
throw DecodingError.dataCorruptedError(
in: container,
debugDescription: "Empty String cannot be converted to Character."
)
}
guard string.count == 1 else {
throw DecodingError.dataCorruptedError(
in: container,
debugDescription: "Multi-character String cannot be converted to Character."
)
}
self = character
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment