你确定你真的想要一个数组中的字典吗?您给出的代码表明更多具有命名列的数组,可以使用以下内容来实现:
struct Name {
var firstName : String
var lastName : String
}
var persons1 : Array<Name> = [
Name(firstName: "Foo", lastName: "Bar"),
Name(firstName: "John", lastName: "Doe")
]
persons1[0].firstName // "Foo"
var persons2 : Array<(firstName: String, lastName:String)> = [
(firstName: "Mary", lastName: "Mean"),
(firstName: "Foo", lastName: "Bar"),
(firstName: "John", lastName: "Doe")
]
persons2[1].firstName // "Bar"
这些是正确的数组,并使用下标来寻址。字典类型通常是键和值的组合,即昵称作为键,名称作为值。
var nickNames : [String:String] = [
"mame" : "Mary Mean",
"foba" : "Foo Bar",
"jodo" : "John Doe"]
nickNames["mame"]! // "Mary Mean"
在这里我们查找键值,并得到一个可选值作为回报,我强行解开它......
所有这些都可以很容易地附加,但请注意命名的元组变体 ,persons2
不遵循推荐的做法。另请注意,字典数组允许包含在我上次注入中建议的不同键中。
persons1.append( Name(firstName: "Some", lastName: "Guy") )
persons2.append( firstName: "Another", lastName: "Girl" )
nickNames["anna"] = "Ann Nabel"
// Array of Dictionaries
var persons : [[String:String]] = [
[ "firstName" : "Firstly", "lastName" : "Lastly"],
[ "firstName" : "Donald", "lastName" : "Duck"]
]
persons.append( ["firstName" : "Georg", "middleName" : "Friedrich", "lastName" : "Händel"] )