简体   繁体   English

从CloudKit Swift获取独特的价值

[英]Fetching distinct values from cloudkit swift

I have a database students with columns : courseID, StudentID,FirstName, LastName 我有一个数据库学生,其列为:courseID,StudentID,FirstName,LastName

Now a student can take more than one course. 现在,一个学生可以修多门课程。

I have a screen where I am fetching just the students names. 我有一个屏幕,仅在其中提取学生姓名。 And so obviously I am getting duplicate values. 所以很明显我得到了重复的值。 Now I know I can change the type of courseID from string to a string list to do away this problem but that would mean a hell lot of coding changes. 现在,我知道可以将CourseID的类型从字符串更改为字符串列表,以解决此问题,但这将意味着大量的代码更改。 is there anyway I can modify my CKQuery to fetch distinct values? 无论如何,我可以修改CKQuery来获取不同的值吗?

As of now the code looks like this: 到目前为止,代码如下所示:

func FetchRecords(){
        print("Fetch Records")
        let predicate = NSPredicate(value: true)
        let query = CKQuery(recordType: "Students", predicate: predicate)
        let operation = CKQueryOperation(query: query)
        operation.desiredKeys = ["FirstName","LastName","StudentID"]

        var newStud = [Student]()
        print("Begin")
        operation.recordFetchedBlock = { (record)  in
            let stud_rec = Student()
            print(record["FirstName"] as! String)
            stud_rec.FName = (record["FirstName"] as! String)
            stud_rec.LName = (record["LastName"] as! String)
            stud_rec.MatrN = (record["StudentID"] as! String)
            newStud.append(stud_rec)
        }

Amrita I think there is data model design issue where you have felt one of consequences -- a lot of "duplicate values". Amrita,我认为存在一个数据模型设计问题,您会感到其中的一种后果-许多“重复的价值”。

The root solution is to avoid many-many relationship between courseID and studentID via a record type say Enrollment to track which student takes which course at which year. 根本解决方案是通过记录类型“注册”来避免课程ID和学生ID之间的多对多关系,以跟踪哪个学生在哪一年修哪门课程。 This of course demands a "hell lot of coding change." 当然,这需要“大量的代码更改”。 that you also want to avoid. 您也要避免。

So maybe you may try this quick surface patch to "fetch distinct values" where you may use Swift Set operations to deal with fetched duplicates as below: 因此,也许您可​​以尝试使用此快速表面补丁来“获取不同的值”,在其中可以使用Swift Set操作来处理获取的重复项,如下所示:

let fetchedDuplicate = ["Jon", "Sid", "Tom", "Jon"]
let uniqueSet = Set(fetchedDuplicate) // it is now {"Jon", "Sid", "Tom"}
let uniqueArray = Array(uniqueSet) // ["Jon", "Sid", "Tom"]

I hope it helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM