A way easier to create JSON body from a bunch of parameters.

Updated
Feb 3, 2021 1:37 PM
Created
Feb 3, 2021 1:33 PM
Tags
SwiftMemo
Keywords
enum MyRequestTrait: RequestParameterFragmentTrait {}

extension RequestParameterFragment where Trait == MyRequestTrait {

	public static func nickname(_ value: String) -> Self {
    .init(jsonKey: "nickname", jsonValue: .init(value))
  }

}

func request(parameters: [RequestParameterFragment<MyRequestTrait>]) {
  ...
}


request(parameters: [
  .nickname("hiroshi")
])

public protocol RequestParameterFragmentTrait {}

public struct RequestParameterFragment<Trait: RequestParameterFragmentTrait>: Hashable {
  
  public let jsonKey: String
  public let jsonValue: JSON
  
  init(jsonKey: String, jsonValue: JSON) {
    self.jsonKey = jsonKey
    self.jsonValue = jsonValue
  }
  
  func applyParameter(to json: inout JSON) {
    json[jsonKey] = json
  }
  
}