Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add nested decoding #12

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions Sources/Codextended/Codextended.swift
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,31 @@ public extension Decoder {
return try container.decode(type, forKey: key)
}

/// Decode a nested value for array of keys, specified as a `CodingKey`.
/// Throws an error if keys array is empty
func decode<T: Decodable>(_ keys: [CodingKey], as type: T.Type = T.self) throws -> T {

// Throw an error here?
guard !keys.isEmpty else {
throw CodextendedDecodingError.emptyCodingKey
}

let keys = keys.map({AnyCodingKey($0.stringValue)})

var container = try self.container(keyedBy: AnyCodingKey.self)
for key in keys.dropLast() {
container = try container.nestedContainer(keyedBy: AnyCodingKey.self, forKey: key)
}
return try container.decode(type, forKey: keys.last!)
}

/// Decode a nested value for array of keys, specified as a string.
/// Throws an error if keys array is empty
func decode<T: Decodable>(_ keys: [String], as type: T.Type = T.self) throws -> T {
return try decode(keys.map({AnyCodingKey($0)}))
}


/// Decode an optional value for a given key, specified as a string. Throws an error if the
/// specified key exists but is not able to be decoded as the inferred type.
func decodeIfPresent<T: Decodable>(_ key: String, as type: T.Type = T.self) throws -> T? {
Expand Down Expand Up @@ -142,6 +167,19 @@ public extension Decoder {
}
}

// MARK: - Errors

public enum CodextendedDecodingError: Error, LocalizedError {
case emptyCodingKey

public var errorDescription: String? {
switch self {
case .emptyCodingKey:
return "Coding keys array was empty"
}
}
}

// MARK: - Date formatters

/// Protocol acting as a common API for all types of date formatters,
Expand Down
57 changes: 56 additions & 1 deletion Tests/CodextendedTests/CodextendedTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,58 @@ final class CodextendedTests: XCTestCase {
}
}

func testDecodingNested() throws {
struct Value: Decodable, Equatable {
let string: String

init(from decoder: Decoder) throws {
string = try decoder.decode(["a","b","c"])
}
}

let jsonString = #"""
{
"a": {
"b": {
"c": "hello world"
}
}
}
"""#

let value = try Data(jsonString.utf8).decoded() as Value
XCTAssertEqual(value.string, "hello world")
}

func testDecodingSingleValueNested() throws {
struct Value: Decodable, Equatable {
let string: String

init(from decoder: Decoder) throws {
string = try decoder.decode(["a"])
}
}

let value = try Data(#"{"a": "hello world"}"#.utf8).decoded() as Value
XCTAssertEqual(value.string, "hello world")
}

func testDecodingNestedWithEmptyKeysThrows() {
struct Value: Decodable, Equatable {
let string: String

init(from decoder: Decoder) throws {
string = try decoder.decode([String]())
}
}

let data = Data(#"{"a": "hello world"}"#.utf8)
XCTAssertThrowsError(try data.decoded() as Value) { error in
XCTAssertEqual(error as? CodextendedDecodingError, CodextendedDecodingError.emptyCodingKey,
"Expected CodextendedDecodingError.emptyCodingKey but got \(error)")
}
}

func testAllTestsRunOnLinux() {
verifyAllTestsRunOnLinux(excluding: ["testDateWithISO8601Formatter"])
}
Expand All @@ -226,6 +278,9 @@ extension CodextendedTests: LinuxTestable {
("testUsingStringAsKey", testUsingStringAsKey),
("testUsingCodingKey", testUsingCodingKey),
("testDateWithCustomFormatter", testDateWithCustomFormatter),
("testDecodingErrorThrownForInvalidDateString", testDecodingErrorThrownForInvalidDateString)
("testDecodingErrorThrownForInvalidDateString", testDecodingErrorThrownForInvalidDateString),
("testDecodingNested", testDecodingNested),
("testDecodingSingleValueNested", testDecodingSingleValueNested),
("testDecodingNestedWithEmptyKeysThrows", testDecodingNestedWithEmptyKeysThrows)
]
}