循环访问字典并创建对象实例



考虑这个字典:

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 实例?

如果不是从NSObject继承的,则应考虑使用结构而不是类。 请注意,当使用结构时,它已经提供了一个默认的初始值设定项,如果它与你的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"

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

// 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)") }

最新更新