Skip to content

Instantly share code, notes, and snippets.

@Machx
Created June 26, 2023 00:02
Show Gist options
  • Save Machx/ca0ccb52170c052348da0ff81b045f26 to your computer and use it in GitHub Desktop.
Save Machx/ca0ccb52170c052348da0ff81b045f26 to your computer and use it in GitHub Desktop.
Decode Type from JSON String
import Foundation
extension Decodable {
init(_ json: String) throws {
self = try JSONDecoder().decode(Self.self, from: json.data(using: .utf8)!)
}
}
struct Thing: Codable {
let text: String
let number: Int
}
let json = #"{"text":"this is text","number":12}"#
let thing = try Thing(json)
print(thing)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment