lytics / ios-sdk

MIT License
0 stars 0 forks source link

Add DictKey #106

Closed mgacy closed 1 year ago

mgacy commented 1 year ago

Adds a DictKey type to access values in nested dictionaries. It is intended primarily to support removal of identifier values. Usage looks like:

var dict: [String: Any] = [
    "outer": [
        "inner": 5
    ]
]

let current = dict[dictPath: "outer.inner"] // 5
dict[dictPath: "outer.inner"] = 6 // ["outer": ["inner": 6]]

One aspect of the subscript implementation worth noting is that empty dictionaries are removed when removing values. For example:

var dict: [String: Any] = [
    "a": [
        "b": [
            "c": "d"
        ]
    ]
]

dict[dictPath: "a.b.c"] = nil
print(dict) // [:]

This serves to mimic how JSONEncoder encodes nil values:

struct B: Codable {
    let c: String?
}

struct A: Codable {
    let b: B?
}

struct Outer: Codable {
    let a: A?
}

print(String(decoding: try JSONEncoder().encode(Outer(a: nil)), as: UTF8.self)) // `{}`