Last active
July 1, 2020 07:15
-
-
Save cweinberger/9290db58a404071b9e439cc114c3d754 to your computer and use it in GitHub Desktop.
IntOrString
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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