Swift-向字典中的数组添加值

时间:2018-11-23 19:56:40

标签: arrays swift dictionary

我有一个对象数组,要根据学生ID将其存储在字典中。在我的字典中,我的键是String类型,而value是一个字符串数组。如何将值附加到数组中?

我的学生数组:

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]),但是却没有输出。

如何将值附加到字典中的数组?

3 个答案:

答案 0 :(得分:2)

这里的每个人都过于复杂。有专门的API可以完成此任务,大声笑

struct Student {
    let id: Int
    let subject: String
}

let students = [
    Student(id: 1, subject: "History"),
    Student(id: 2, subject: "History"),
    Student(id: 1, subject: "Maths")
]

let subjectsByStudentID = Dictionary
    .init(grouping: students, by: { $0.id })
    .mapValues { students in students.map { $0.subject } }

print(subjectsByStudentID) // => [2: ["History"], 1: ["History", "Maths"]]

答案 1 :(得分:1)

编辑:感谢Martin的评论。下面的代码段是我能想到的最简洁的答案。我最初是从错误的方向走过来。而我得到一个错误。查看评论

function pop (array){
  let last = array[array.length-1];  // Store last item in array
  array.length = array.length > 0 ? array.length - 1 : 0; // Decrease length
  return last; // Return last item
}

// Test function
function logger(ary){
  console.log("Original array: " + ary.join(", "), "\n\tItem popped off: " + pop(ary), "\n\tArray contents now: " + ary.join(", "));
}

// Tests
var ary = [1,2,3,4]; logger(ary);
var ary = ["red", "white", "blue", "green"]; logger(ary);
var ary = ["onlyItem"]; logger(ary);
var ary = []; logger(ary);
var ary = [false]; logger(ary);

上一个答案:

struct Student { 
    let id: Int
    let subject : String
}

var studentArray = [Student(id: 1, subject: "History"), Student(id: 2, subject: "History"), Student(id:1, subject: "Maths")]

typealias Subject = String
var dict : [Int: [Subject]] = [:]

for student in studentArray {

    (dict[student.id, default: []]).append(student.subject)
}

print(dict)

或者您可以这样操作:

struct Student { 
    let id: Int
    let subject : String
}

var studentArray = [Student(id: 1, subject: "History"), Student(id: 2, subject: "History"), Student(id:1, subject: "Maths")]

typealias Subject = String
var dict : [Int: [Subject]] = [:]

for student in studentArray {
    var subjects = dict[student.id] ?? [String]()
    subjects.append(student.subject)
    dict[student.id] = subjects
}

print(dict)

任何你喜欢的

答案 2 :(得分:0)

未经测试,但应该可以:

var dictionary = [String: [String]]()

for student in studentArray {
    if dictionary[student.id] == nil {
        dictionary[student.id] = [String]()
    }
    dictionary[student.id]?.append(student.subject)
}