映射对象中的值

时间:2017-06-14 16:11:45

标签: swift object

我的模型看起来像这样:

struct Person {
    let id = 0
    let name = ""
    var comment = String()
}

struct OverAll {
    let person = [Person]
}

我有两个对象:

OverAllPerson // contains 10 persons
OverAlPersonWithComments // contains 10 persons

除了OverAllPerson没有评论

之外,这些对象都是相同的

问题:
如何将OverAlPersonWithComments的评论添加到OverAllPerson?如上所述,除了comments之外,对象是相同的。

我在考虑使用map,但我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

对于您的示例,我只是做一个简单的for循环

for index in 0 ..< peopleWithoutComments.count {
    peopleWithoutComments[index].comment = peopleWithComments[index].comment
}

您可能会想到的模式是zip map。考虑:

let names = ["joe", "bill", "jane"]
let comments = [
    ["I like baseball", "But I don't like the Yankees"],
    ["I don't watch sports"],
    ["I like football", "I'm an Arsenal fan"]
]

struct Person {
    let name: String
    let comments: [String]
}

let people = zip(names, comments).map { (name, comments) in Person(name: name, comments: comments) }