Skip to content

Instantly share code, notes, and snippets.

@cweinberger
Last active July 1, 2020 07:15
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 cweinberger/9290db58a404071b9e439cc114c3d754 to your computer and use it in GitHub Desktop.
Save cweinberger/9290db58a404071b9e439cc114c3d754 to your computer and use it in GitHub Desktop.
IntOrString
import Foundation
enum IntOrString: Encodable {
case integer(Int)
case string(String)
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .integer(let val): try container.encode(val)
case .string(let val): try container.encode(val)
}
}
}
struct Filter: Encodable {
let field: String
let operation: String
let value: IntOrString
}
struct APIRequestBody: Encodable {
let filters: [Filter]
}
let requestBody = APIRequestBody(filters:
[
Filter(field: "handle", operation: "equal", value: .string("cweinberger")),
Filter(field: "age", operation: "lessThan", value: .integer(35))
]
)
let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = .prettyPrinted
let jsonData = try jsonEncoder.encode(requestBody)
print(String(data: jsonData, encoding: .utf8)!)
/*
prints:
{
"filters" : [
{
"field" : "handle",
"operation" : "equal",
"value" : "cweinberger"
},
{
"field" : "age",
"operation" : "lessThan",
"value" : 35
}
]
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment