Skip to content

Commit

Permalink
Merge pull request #7 from mt81/master
Browse files Browse the repository at this point in the history
Decoding optional values
  • Loading branch information
tattn authored Dec 11, 2018
2 parents 4b8ac42 + 280f652 commit d43014f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
6 changes: 5 additions & 1 deletion Sources/URLQueryItemsDecoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ extension URLQueryItemsDecoder {
return try container.first(where: { $0.name == key.stringValue })
.unwrapOrThrow(error: decoder.notFound(key: key))
}

private func isNill(forKey key: CodingKey) throws -> Bool {
return container.first(where: { $0.name == key.stringValue }) == nil
}

func _decode<T: Decodable & LosslessStringConvertible>(_ type: T.Type, forKey key: Key) throws -> T {
let value = try find(forKey: key)
Expand All @@ -108,7 +112,7 @@ extension URLQueryItemsDecoder {
return try decoder.unbox(value, as: T.self)
}

func decodeNil(forKey key: Key) throws -> Bool { throw decoder.notFound(key: key) }
func decodeNil(forKey key: Key) throws -> Bool { return try isNill(forKey: key) }
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return try _decode(type, forKey: key) }
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return try _decode(type, forKey: key) }
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return try _decode(type, forKey: key) }
Expand Down
34 changes: 34 additions & 0 deletions Tests/URLQueryItemsDecoderTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,39 @@ class URLQueryItemsDecoderTests: XCTestCase {
XCTAssertEqual(parameter.string, params[0].value)
XCTAssertEqual(parameter.int.description, params[1].value)
XCTAssertEqual(parameter.double.description, params[2].value)

}

func testDecodeOptionalParameter() throws {
struct Parameter: Codable {
let string: String?
let int: Int?
let double: Double?
}
let params: [URLQueryItem] = [
URLQueryItem(name: "string", value: "abc"),
URLQueryItem(name: "int", value: "123"),
URLQueryItem(name: "double", value: Double.pi.description)
]
let parameter = try decoder.decode(Parameter.self, from: params)

XCTAssertEqual(parameter.string, params[0].value)
XCTAssertEqual(parameter.int?.description, params[1].value)
XCTAssertEqual(parameter.double?.description, params[2].value)
}

func testDecodeEmptyOptionalParameter() throws {
struct Parameter: Codable {
let string: String?
let int: Int?
let double: Double?
}
let params: [URLQueryItem] = [
]
let parameter = try decoder.decode(Parameter.self, from: params)

XCTAssertEqual(parameter.string, nil)
XCTAssertEqual(parameter.int, nil)
XCTAssertEqual(parameter.double, nil)
}
}

0 comments on commit d43014f

Please sign in to comment.