【发布时间】:2018-11-24 05:49:10
【问题描述】:
我有一个对象数组,我想根据学生 ID 将其存储在字典中。在我的字典中,我的键是字符串类型,值是字符串数组。如何在数组中附加值?
我的学生数组:
var studentArray = [Student(id: '1', subject: 'History'), Student(id: '2', subject: 'History'), Student(id:'1', subject: 'Maths')]
我的最终字典应该是这样的:
{'1': ['History', 'Maths'], '2': ['History']}
我的代码:
var dictionary = [String, [String]]()
for student in studentArray {
dictionary.updateValue(student.subject, forKey: student.id)
}
这给了我输出:
{'1': ['Maths'], '2': ['History']}
我试过:dictionary[student.id].append([student.subject]) 但这给了我零输出。
如何将值附加到字典内的数组中?
【问题讨论】:
标签: arrays swift dictionary