Skip to content

Instantly share code, notes, and snippets.

@iamchiwon
Created December 5, 2022 08:48
Show Gist options
  • Save iamchiwon/214d54a9566fa38baf893083f2e2ce50 to your computer and use it in GitHub Desktop.
Save iamchiwon/214d54a9566fa38baf893083f2e2ce50 to your computer and use it in GitHub Desktop.
import Foundation
extension JSONDecoder {
static func decodeFromString<T: Decodable>(_ type: T.Type, from: String) -> T? {
guard let data = from.data(using: .utf8) else { return nil }
return try? JSONDecoder().decode(type, from: data)
}
}
extension JSONEncoder {
static func encodeToString<T: Encodable>(value: T) -> String? {
guard let data = try? JSONEncoder().encode(value) else { return nil }
return String(data: data, encoding: .utf8)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment