Created
June 26, 2023 00:02
-
-
Save Machx/ca0ccb52170c052348da0ff81b045f26 to your computer and use it in GitHub Desktop.
Decode Type from JSON String
This file contains 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
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