Skip to content

Instantly share code, notes, and snippets.

@omatty198
Created October 20, 2019 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omatty198/b86a04efcfdbe8217ffcd3e51de9f6cf to your computer and use it in GitHub Desktop.
Save omatty198/b86a04efcfdbe8217ffcd3e51de9f6cf to your computer and use it in GitHub Desktop.
hoge_decode_test.swift
import XCTest
class WassyoiTests: XCTestCase {
override func setUp() {
}
override func tearDown() {
}
func testDecodeHogeInfo() {
let data = """
{
"hoge_key": null
}
""".data(using: .utf8)!
var i: HogeInfo?
do {
i = try JSONDecoder().decode(HogeInfo.self, from: data)
} catch let DecodingError.dataCorrupted(context) {
print(context)
XCTFail("should be decoded.")
} catch let DecodingError.keyNotFound(key, context) {
print("Key '\(key)' not found:", context.debugDescription)
print("codingPath:", context.codingPath)
XCTFail("should be decoded.")
} catch let DecodingError.valueNotFound(value, context) {
print("Value '\(value)' not found:", context.debugDescription)
print("codingPath:", context.codingPath)
XCTFail("should be decoded.")
} catch let DecodingError.typeMismatch(type, context) {
print("Type '\(type)' mismatch:", context.debugDescription)
print("codingPath:", context.codingPath)
XCTFail("should be decoded.")
} catch {
print("error: ", error)
XCTFail("should be decoded.")
}
print(i?.hoge)
XCTAssertNil(i?.hoge)
}
}
struct HogeInfo {
let hoge: Hoge?
}
extension HogeInfo: Codable {
enum Keys: String, CodingKey {
case hogeKey = "hoge_key"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Keys.self)
////////////////////////////////↓ここにハテナいるねん/////////////////////////////
hoge = try container.decode(Hoge?.self, forKey: .hogeKey)
}
}
struct Hoge: Codable {
let id: Int
let title: String
let url: URL
}
extension Hoge {
enum CodingKeys: String, CodingKey {
case id
case title
case url
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
title = try container.decode(String.self, forKey: .title)
url = try container.decode(URL.self, forKey: .url)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment