简体   繁体   中英

Swift - How can I add an expand a nested dictionary?

I have want to add en entry to this kind of Array/Tuple/Dictionary data :

var i=0
var data = [("foo", ["first": 1, "second": 2]), ("bar", ["first": 1, "second": 2])] 
var newData = [(Int, [String: AnyObject])]()
for (key, value) in data {

    newData.append((i, value))

    i = i+1
}

The for loop is changing the "key" of the tuple which is AnyObject to an Int. I want the Tuple to have the key as dictionary too.

[("foo", ["first": 1, "second": 2]),
 ("bar", ["first": 1, "second": 2])] 

turns into

 [(1, ["first": 1, "second": 2]), 
  (2, ["first": 1, "second": 2])] 

and what I want is:

 [(1, ["first": 1, "second": 2, "key": "foo"]), 
  (2, ["first": 1, "second": 2, "key": "bar"])] 

Starting from

let data: [(String, [String: AnyObject])] = [
    ("foo", ["first": 1, "second": 2]),
    ("bar", ["first": 1, "second": 2])]

this is a variants that doesn't require a separate counting variable

let newData = data.map({ (var e) -> [String: AnyObject] in
    e.1.updateValue(e.0, forKey: "key")
    return e.1
}).enumerate().map({ ($0.0 + 1, $0.1) })

The enumerate call could also be moved to the front which makes the block signature a little less compact, however.

let newData = data.enumerate().map { (var e) -> ((Int, [String: AnyObject])) in
    e.1.1.updateValue(e.1.0 , forKey: "key")
    return (e.0 + 1, e.1.1)
}

Both variants result in

[(1, ["first": 1, "second": 2, "key": "foo"]),
 (2, ["first": 1, "second": 2, "key": "bar"])]

Try this

var data = [("foo", ["first": 1, "second": 2]), ("bar", ["first": 1, "second": 2])]

var i = 0
var newData = [(Int, [String: AnyObject])]()
for (key, value) in data {

  var newValue : [String:AnyObject] = value
  newValue["key"] = key
  newData.append((++i, newValue))
}

print(newData)

or with the Swift map function

var i = 0
let newData = data.map { (key, value) -> (Int, [String: AnyObject]) in
  var newValue = value
  newValue["key"] = key
  return (++i, newValue)
}

print(newData)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM