Last active
November 5, 2020 11:28
-
-
Save vzsg/bcb31d2afb0c8ae3116936fd1cca14d0 to your computer and use it in GitHub Desktop.
This file contains 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 | |
struct Property: Encodable { | |
let name: String | |
@AnyEncodable | |
var value: Encodable | |
} | |
@propertyWrapper struct AnyEncodable: Encodable { | |
let wrappedValue: Encodable | |
func encode(to encoder: Encoder) throws { | |
try wrappedValue.encode(to: encoder) | |
} | |
} | |
let prop1 = Property(name: "int", value: 5) | |
let prop2 = Property(name: "string", value: "Hello!") | |
let prop3 = Property(name: "nestedArray", value: [prop1, prop2]) | |
let prop4 = Property(name: "wtf", value: ["deep": prop3]) | |
let jsonEncoder = JSONEncoder() | |
print(try String(data: jsonEncoder.encode(prop1), encoding: .utf8)!) | |
print(try String(data: jsonEncoder.encode(prop2), encoding: .utf8)!) | |
print(try String(data: jsonEncoder.encode(prop3), encoding: .utf8)!) | |
print(try String(data: jsonEncoder.encode(prop4), encoding: .utf8)!) | |
/* | |
Prints: | |
{"name":"int","value":5} | |
{"name":"string","value":"Hello!"} | |
{"name":"nestedArray","value":[{"name":"int","value":5},{"name":"string","value":"Hello!"}]} | |
{"name":"wtf","value":{"deep":{"name":"nestedArray","value":[{"name":"int","value":5},{"name":"string","value":"Hello!"}]}}} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment