Last active
March 19, 2021 18:14
-
-
Save rgajrawala/f3d009b2505f67f8ca3c28f317f03f0b to your computer and use it in GitHub Desktop.
Hack for "AnyCodable" for encoding an array of generic structs.
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
// https://stackoverflow.com/a/66697096/2006429 | |
import Foundation | |
enum ChangeOp: String, Encodable { | |
case replace | |
case append | |
} | |
enum ChangePath: String, Encodable { | |
case name = "/info/name" | |
case number = "/info/number" | |
case location = "/info/location" | |
case showLocation = "/privacy/showLocation" | |
} | |
enum ChangeValue { | |
case string(String) | |
case int(Int) | |
case stringArray([String]) | |
case bool(Bool) | |
} | |
extension ChangeValue: Encodable { | |
func encode(to encoder: Encoder) throws { | |
var container = encoder.singleValueContainer() | |
switch self { | |
case .string(let value): | |
try container.encode(value) | |
case .int(let value): | |
try container.encode(value) | |
case .stringArray(let value): | |
try container.encode(value) | |
case .bool(let value): | |
try container.encode(value) | |
} | |
} | |
} | |
public struct UserChange: Encodable { | |
let op: ChangeOp | |
let path: ChangePath | |
var value: ChangeValue | |
enum CodingKeys: CodingKey { | |
case op, path, value | |
} | |
} | |
func encodeChanges(arr: [UserChange]) -> String? { | |
let encoder = JSONEncoder() | |
guard let jsonData = try? encoder.encode(arr) else { | |
return nil | |
} | |
return String(data: jsonData, encoding: String.Encoding.utf8) | |
} | |
func requestUserChanges(changes: String) { | |
print(changes) | |
// make API request ... | |
} | |
requestUserChanges(changes: | |
encodeChanges(arr: [ | |
UserChange(op: .replace, path: .name, value: .string("TestName")), | |
UserChange(op: .replace, path: .number, value: .int(100)), | |
UserChange(op: .replace, path: .location, value: .stringArray(["STATE", "CITY"])), | |
UserChange(op: .replace, path: .showLocation, value: .bool(true)), | |
]) ?? "null" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment