Skip to content

Instantly share code, notes, and snippets.

@rnapier
Created July 20, 2018 00:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rnapier/a5e8b412d0b268fae02e8db9b6f122a8 to your computer and use it in GitHub Desktop.
Save rnapier/a5e8b412d0b268fae02e8db9b6f122a8 to your computer and use it in GitHub Desktop.
JSONEncoder().stringEncode()
extension JSONEncoder {
func stringEncode<T>(_ value: T) throws -> String where T : Encodable {
guard let string = String(data: try self.encode(value), encoding: .utf8) else {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Could not UTF-8 encode string"))
}
return string
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment