Skip to content

Instantly share code, notes, and snippets.

@Lavmint
Created November 11, 2018 04:15
Show Gist options
  • Save Lavmint/95a8cfd6376e7b3999655734e968c0e4 to your computer and use it in GitHub Desktop.
Save Lavmint/95a8cfd6376e7b3999655734e968c0e4 to your computer and use it in GitHub Desktop.
Encode optionals to requests with Encodable
import Foundation
enum EncodableOptional<Wrapped>: ExpressibleByNilLiteral {
case none
case some(Wrapped)
init(nilLiteral: ()) {
self = .none
}
}
extension EncodableOptional: Encodable where Wrapped: Encodable {
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .none:
try container.encodeNil()
case .some(let wrapped):
try wrapped.encode(to: encoder)
}
}
}
extension EncodableOptional{
var value: Optional<Wrapped> {
get {
switch self {
case .none:
return .none
case .some(let v):
return .some(v)
}
}
set {
switch newValue {
case .none:
self = .none
case .some(let v):
self = .some(v)
}
}
}
}
struct User: Encodable {
var name: String
var surname: String
var age: Int?
var gender: EncodableOptional<String>
}
func main() {
var user = User(name: "William", surname: "Lowson", age: 36, gender: nil)
user.gender.value = "male"
user.gender.value = nil
print(user.gender.value ?? "")
let jsonEncoder = JSONEncoder()
let data = try! jsonEncoder.encode(user)
let json = try! JSONSerialization.jsonObject(with: data, options: [])
print(json)
let dict: [String: Any?] = [
"gender": nil
]
let d = try! JSONSerialization.data(withJSONObject: dict, options: [.prettyPrinted])
let j = try! JSONSerialization.jsonObject(with: d, options: [])
print(j)
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment