迭代字典并创建Object实例

时间:2018-01-12 14:03:37

标签: swift object dictionary instance

考虑这个词典:

var studentList = [ "Paul": 5, "Mike": 7, "Ralph": 9, "Graham": 11, "Steve": 12, "Joe": 14, "Truman": 15, "Rick": 16, "Thomas": 17]

以下对象:

class Student {
   var name: String
   var note: Int

   init(name: String, note: Int) {
     self.name = name
     self.note = note
   }
}

我想遍历studentList,以便创建具有属性名称的Student()实例,并通过键和字典的值实现注释以获得此结果:

student1(name: Paul, note: 5)
student2(name: Mike, note: 9)
....

我应该如何修改我的Student对象以及我应该使用哪种函数(我已尝试使用map {})来创建我的Student实例?

2 个答案:

答案 0 :(得分:1)

如果您不是从NSObject继承,则应考虑使用结构而不是类。请注意,当使用struct时,它已经提供了一个默认初始值设定项,如果它与你的map元素(String,Int)匹配,你可以将初始化方法传递给map方法,不需要使用闭包:

struct Student {
    let name: String
    let note: Int
}

let students =  studentList.map(Student.init)

如果您想自定义结构的打印方式,可以按照@ user28434的建议使其符合CustomStringConvertible,并实现描述属性:

extension Student: CustomStringConvertible {
    var description: String {
        return "Name: \(name) - Note: \(note)"
    }
}

print(students)   // "[Name: Graham - Note: 11, Name: Rick - Note: 16, Name: Steve - Note: 12, Name: Paul - Note: 5, Name: Thomas - Note: 17, Name: Ralph - Note: 9, Name: Joe - Note: 14, Name: Truman - Note: 15, Name: Mike - Note: 7]\n"

答案 1 :(得分:0)

map(_ :)适用于您的用例,对于类型字典的输入结构,语法非常复杂($ 0是Key,$ 1是Value):

// I want to iterate through studentList in order to create instances of Student() with the properties name and note implemented by the key and the value of the dictionary
// How should I modify my Student object and what kind function should I use (I've tried with map{} ) to create my Student instances?
var students: [Student] = studentList.map { return Student(name: $0, note: $1) }

关于您的评论,根据学生排名添加类别,如果您希望类别是学生类的实例,您必须在学生之间存储共享信息,因此我们将引入静态变量。

更改您的学生课程如下:

class Student {

    public enum CategoryType {
        case junior
        case intermediate
        case senior
    }

    static var studentNotes = [Int]()
    var name: String
    var note: Int
    var category: CategoryType {
        get {
            let sortedStudentNotes = Student.studentNotes.sorted { $0 > $1 }

            var rank = Student.studentNotes.count
            for i in 0..<sortedStudentNotes.count {
                if sortedStudentNotes[i] == self.note {
                    rank = (i + 1)
                    break
                }
            }

            return (1 <= rank && rank <= 3) ? .junior
            : ((4 <= rank && rank <= 6) ? .intermediate : .senior)
        }
    }

    init(name: String, note: Int) {
        self.name = name
        self.note = note
        Student.studentNotes.append(note)
    }
}

最后,您可以打印学生类别:

// How can I split these result into 3 categories junior, intermediate and senior.
// These 3 categories must be instances of the class Student.
// static var studentNotes: Int[]
students.forEach { print("\($0.name) is \($0.category)") }