Skip to content

Instantly share code, notes, and snippets.

@josevazquez
Created June 16, 2023 17:44
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josevazquez/0c1b51d46960b51ee4fe6b5432bc9800 to your computer and use it in GitHub Desktop.
Save josevazquez/0c1b51d46960b51ee4fe6b5432bc9800 to your computer and use it in GitHub Desktop.
Add parse() from a json string to any Decodable
import XCTest
extension Decodable {
init(_ json: String) throws {
self = try JSONDecoder().decode(Self.self, from: json.data(using: .utf8)!)
}
}
final class DecodableExtensions: XCTestCase {
struct Dummy: Codable {
let text: String
let number: Double
}
func testParse() throws {
let json = #"{"text": "someString", "number": 123.45}"#
let dummy = try Dummy(json)
XCTAssertEqual(dummy.text, "someString")
XCTAssertEqual(dummy.number, 123.45)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment