How to update a value in a nested dictionary given path fragment in Swift?

前端 未结 2 1820
不知归路
不知归路 2021-01-21 13:52

I have a nested dictionary and an array containing path fragment. I need to update the value at that location.

I am possibly looking for a recursive function instead of

2条回答
  •  后悔当初
    2021-01-21 14:37

    This is not what you asked, but the entire premise here is unSwifty. The use of [String:Any] is a Bad Smell. It seems more like Objective-C. And indeed this whole thing is a one-liner in Objective-C:

    NSMutableDictionary * d1 = [[NSMutableDictionary alloc] initWithDictionary: @{ @"title" : @1111 }];
    NSMutableDictionary * d2 = [[NSMutableDictionary alloc] initWithDictionary: @{ @"item" : d1 }];
    NSMutableDictionary * d3 = [[NSMutableDictionary alloc] initWithDictionary: @{ @"channel" : d2 }];
    

    Okay, that was just to prepare the data. Here’s the one-liner:

    [d3 setValue:@123 forKeyPath:@"channel.item.title"];
    

    But I would question the entire nested dictionaries concept; it seems to me you’ve gone down a wrong well here and you need to stand back and rethink your data structure.

提交回复
热议问题