我有一个AnyObject类型数组,如下所示:[[String:AnyObject]]
animalList = [[" name":ABC," color":red],[" name":DEF," color" : 绿色],["名称":GHI,"颜色":蓝色]]
模型类是这样的:
class ModelAnimal {
var name: String
var color: String
init(name: String, color: String){
self.name = name
self.color = color
}
}
如何将它们放入ModelAnimal类型的数组中:
var myList = Array<ModelAnimal>()
for var i = 0; i < animalList.count; i++ {
myList.
}
答案 0 :(得分:5)
使用map
创建一个类型为[ModelAnimal]
的新数组:
let animalList: [[String: AnyObject]] = [["name": "ABC", "color":"red"], ["name": "DEF", "color": "green"], ["name": "GHI", "color": "blue"]]
class ModelAnimal {
var name: String
var color: String
init(name: String, color: String){
self.name = name
self.color = color
}
}
let myList = animalList.map { ModelAnimal(name: $0["name"] as? String ?? "", color: $0["color"] as? String ?? "") }
这也使用了条件转换 as? String
以及 nil合并运算符 ??
来安全地从字典数组中提取值并将它们传递给ModelAnimal
的构造函数。
答案 1 :(得分:3)
首先,建议使用Struct
代替Class
模型。
为什么选择Struct?
failable init
,它可以在不初始化所有存储属性的情况下返回失败。name
和color
字段不会改变,您应该将它们声明为let
。这样你的Struct将完全不可变(这有几个原因)。 为您的模型添加failable inititializer
以接收可选参数
struct ModelAnimal {
let name: String // you can change this back to var if needed
let color: String // you can change this back to var if needed
init(name: String, color: String){
self.name = name
self.color = color
}
init?(name: String?, color: String?) {
guard let name = name, color = color else { return nil }
self.name = name
self.color = color
}
}
现在您可以使用强大的flapMap
功能
let animals = animalList.flatMap { ModelAnimal(name: $0["name"], color: $0["color"]) }
为何选择flatMap?
flatMap
的美妙之处在于它确实只返回非零值。
Infact animalList
包含非结构化数据,您无法保证(至少在编译时)每个元素都有name
和color
键。这样,如果错误数据包含在animalList
中,则会被丢弃。flatMap
的另一个好处是它确实返回array
ModelAnimal
,而不是ModelAnimal?
。答案 2 :(得分:0)
首先initialize
您的ModelAnimal对象,然后将它们添加到数组中:
let animalOne = ModelAnimal(name: "ABC", color: "red")
let animalTwo = ModelAnimal(name: "DEF", color: "green")
let animalThree = ModelAnimal(name: "GHI", color: "blue")
let myList: Array<ModelAnimal> = [animalOne, animalTwo, animalThree]
您也可以在线执行此操作:
let myList: Array<ModelAnimal> = [ModelAnimal(name: "ABC", color: "red"), ModelAnimal(name: "DEF", color: "green"), ModelAnimal(name: "GHI", color: "blue")]
答案 3 :(得分:0)
代码只是迭代animalList
并将新项目添加到myList
:
var myList = Array<ModelAnimal>()
for var i = 0; i < animalList.count; i++ {
myList.append(ModelAnimal(name: animalList[i]["name"]!, color: animalList[i]["color"]!))
}
它有效,但每次调用append
都不利于性能。实现这一目标的更好方法是创建具有所需长度的数组:
for var i = 0; i < animalList.count; i++ {
myList[i] = ModelAnimal(name: animalList[i]["name"]!, color: animalList[i]["color"]!)
}