Created
June 2, 2020 20:17
-
-
Save john-mueller/cb5fe3d39afe47ad7c94a84a6670e010 to your computer and use it in GitHub Desktop.
Codable conformance for Swift's Character
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
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