Created
June 16, 2023 17:44
-
-
Save josevazquez/0c1b51d46960b51ee4fe6b5432bc9800 to your computer and use it in GitHub Desktop.
Add parse() from a json string to any Decodable
This file contains hidden or 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 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