从 Swift 中的两个数组生成字典数组
Produce an array of dictionaries from two arrays in Swift
我有两本词典:
name = ["A","B","C","D","E"]
number = ["1","2","3","4","5"]
如何使用内置函数生成以下内容?
[
{name : "A", number: "1"},
{name : "B", number: "2"},
{name : "C", number: "3"},
{name : "D", number: "4"},
{name : "E", number: "5"}
]
您显示的期望结果不是单个字典,而是字典数组,即 [[String: String]]
。
您可以像这样转换两个数组:
name = ["A","B","C","D","E"]
number = ["1","2","3","4","5"]
let result = zip(name, number).map { ["name": [=10=], "number": ] }
但是,我建议您创建一个 struct/class 来存储这些 name/number 对,而不是使用字典数组:
struct Foo { // give this an appropriate name!
let name: string
let number: String
}
let result = zip(name, number).map { Foo(name: [=11=], number; ) }
我有两本词典:
name = ["A","B","C","D","E"]
number = ["1","2","3","4","5"]
如何使用内置函数生成以下内容?
[
{name : "A", number: "1"},
{name : "B", number: "2"},
{name : "C", number: "3"},
{name : "D", number: "4"},
{name : "E", number: "5"}
]
您显示的期望结果不是单个字典,而是字典数组,即 [[String: String]]
。
您可以像这样转换两个数组:
name = ["A","B","C","D","E"]
number = ["1","2","3","4","5"]
let result = zip(name, number).map { ["name": [=10=], "number": ] }
但是,我建议您创建一个 struct/class 来存储这些 name/number 对,而不是使用字典数组:
struct Foo { // give this an appropriate name!
let name: string
let number: String
}
let result = zip(name, number).map { Foo(name: [=11=], number; ) }