我接受上面的答案,它非常好。虽然你已经给出正确的答案,但我喜欢用最简单的方法来解释。如果你们按照以下步骤操作,会很有用。如果有人刚开始学习Swift,并且阅读这篇内容,他们也可以轻松理解这些步骤。
步骤1:声明并初始化变量
var array = Array<AnyObject>()
var dict = Dictionary<String, AnyObject>()
var make = "chevy"
var year = 2008
var color = "red"
步骤2:设置字典(添加键和值)
dict["trackMake"] = make
dict["trackYear"] = year
dict["trackColor"] = color
println("the dict is-\(dict)")
第三步:将字典添加到数组中。
array.append(dict)
println("the array is-\(array)")
步骤 4:将数组值存储到变量中(创建用于获取值的变量)
let getMakeValue = array[0]["trackMake"]
let getYearValue = array[0]["trackYear"]
let getColorValue = array[0]["trackColor"]
println("the getMakeValue is - \(getMakeValue)")
println("the getYearValue is - \(getYearValue)")
println("the getColorVlaue is - \(getColorValue)")
步骤5:如果您想将值转换为字符串,请执行以下步骤
var stringMakeValue:String = getMakeValue as String
var stringYearValue:String = ("\(getYearValue as Int)")
var stringColorValue:String = getColorValue as String
println("the stringMakeValue is - \(stringMakeValue)")
println("the stringYearValue is - \(stringYearValue)")
println("the stringColorValue is - \(stringColorValue)")
步骤6:最终的总输出值为:
the dict is-[trackMake: chevy, trackColor: red, trackYear: 2008]
the array is-[{
trackColor = red;
trackMake = chevy;
trackYear = 2008;
}]
the getMakeValue is - Optional(chevy)
the getYearValue is - Optional(2008)
the getColorVlaue is - Optional(red)
the stringMakeValue is - chevy
the stringYearValue is - 2008
the stringColorValue is - red
Thank You