Skip to content

Commit

Permalink
Fix output of Optional type, add testcase
Browse files Browse the repository at this point in the history
  • Loading branch information
kientux committed Jul 7, 2022
1 parent 90a72e8 commit ae13464
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
35 changes: 29 additions & 6 deletions Sources/Parameterize/Params.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,19 +37,42 @@ extension Params: ParameterPair {

var value: Any? {
if let mapper = mapper {
return process(value: mapper(wrappedValue))
return process(mappedValue: mapper(wrappedValue))
} else {
return process(value: wrappedValue)
return processWrappedValue()
}
}

private func process(value: Any?) -> Any? {
var v: Any? = nil
/// Two functions below have completely the same body
/// but it required to split to 2 functions
/// because with `wrappedValue`, we need to directly access
/// instead of go through `Any?` parameter,
/// or else it will be wrapped into an `Optional<Any>` type
/// and produces incorrect output.

private func processWrappedValue() -> Any? {
var v: Any?

if let value = wrappedValue as? OptionalProtocol {
v = value.wrapped
} else {
v = wrappedValue
}

if let value = v as? ParamConvertible {
v = value.parameterValue
}

return v
}

private func process(mappedValue: Any?) -> Any? {
var v: Any?

if let value = value as? OptionalProtocol {
if let value = mappedValue as? OptionalProtocol {
v = value.wrapped
} else {
v = value
v = mappedValue
}

if let value = v as? ParamConvertible {
Expand Down
8 changes: 8 additions & 0 deletions Tests/ParameterizeTests/ParameterizeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ final class ParameterizeTests: XCTestCase {
productsTypes: ["normal"])
let serialized = ParamSerializer().serialize(object: params)

/// make sure output type is `String`, not `Optional<String>`
XCTAssertEqual("\(serialized["query"] ?? "")", "search")
XCTAssertNotEqual("\(serialized["query"] ?? "")", "Optional(\"search\")")

XCTAssertEqual(serialized["query"] as? String, "search")
XCTAssertEqual(serialized["ids"] as? String, "1,2,3")
XCTAssertEqual(serialized["page"] as? Int, 2)
Expand Down Expand Up @@ -82,6 +86,10 @@ final class ParameterizeTests: XCTestCase {

serialized = ParamSerializer().serialize(object: params)
XCTAssertEqual(serialized["optionalCustomMapper"] as? Int, 101)

/// make sure output type is `Int`, not `Optional<Int>`
XCTAssertEqual("\(serialized["optionalCustomMapper"] ?? 0)", "101")
XCTAssertNotEqual("\(serialized["optionalCustomMapper"] ?? 0)", "Optional(101)")
}
}

Expand Down

0 comments on commit ae13464

Please sign in to comment.