我想在这种Array / Tuple / Dictionary public static void main(String[] args) {
System.out.println(duplicates("aabbbbbb976fkkkkc", '\0'));
}
中添加en条目:
data
for循环正在改变"键"对Int的任何元素的元组。 我希望Tuple也把密钥作为字典。
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
}
变成
[("foo", ["first": 1, "second": 2]),
("bar", ["first": 1, "second": 2])]
我想要的是:
[(1, ["first": 1, "second": 2]),
(2, ["first": 1, "second": 2])]
答案 0 :(得分:1)
从
开始let data: [(String, [String: AnyObject])] = [
("foo", ["first": 1, "second": 2]),
("bar", ["first": 1, "second": 2])]
这是一种不需要单独计数变量的变种
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) })
enumerate
调用也可以移到前面,这使得块签名不那么紧凑。
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)
}
两种变体都会导致
[(1, ["first": 1, "second": 2, "key": "foo"]),
(2, ["first": 1, "second": 2, "key": "bar"])]
答案 1 :(得分:0)
试试这个
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)
或使用Swift map
函数
var i = 0
let newData = data.map { (key, value) -> (Int, [String: AnyObject]) in
var newValue = value
newValue["key"] = key
return (++i, newValue)
}
print(newData)