I'm new to learning Swift myself. Tell me how to create an object data model? Content is such - there is a list of students by classes, and there are several such classes. These data should be displayed in two tables - in one list of classes, in the other - the user selects a class and the list of students is shown to him.

Made this model:

struct Student { var name: String } struct CollegeClass { var title: String var students: [Student] } var collegeClass = CollegeClass(title: "9A", students: ["Ivanov", "Petrov", "Sidorov"]) 

But it gives an error - Cannot convert the value of type 'String' to the expected element type 'Student' What is wrong here? How to create a dictionary, then to transfer data from it to a table?

Update: add secondClass

 arrayCollegeClass.append(CollegeClass(title: "9B", students: [Student(name: "Orlov"), Student(name: "Pavlov"), Student(name: "Semenov")])) 

    1 answer 1

    The students property of the CollegeClass class is a Student array, not a String array. Even though Student has so far only one property, collegeClass needs to be initialized like this:

     var collegeClass = CollegeClass(title: "9A", students: [Student(name: "Ivanov"), Student(name: "Petrov"), Student(name: "Sido")]) 

    If you want students to look more like an array of strings, add this extension:

     extension String { var asStudentName: Student { return Student(name: self) } } 

    And then collegeClass will be initialized like this:

     var collegeClass = CollegeClass(title: "9A", students: ["Ivanov".asStudentName, "Petrov".asStudentName, "Sido".asStudentName]) 

    Suppose that the information about all the classes you have is stored in a similar array:

     let arrayCollegeClass = [ CollegeClass(title: "9A", students: [Student(name: "Ivanov"), Student(name: "Petrov"), Student(name: "Sido")]), CollegeClass(title: "9B", students: [Student(name: "Orlov"), Student(name: "Pavlov"), Student(name: "Semenov")]) ] 

    Then you can get a list of students for a class with a specific name using the following function:

     func students(of classTitle: String, arrayCollegeClass: [CollegeClass]) -> [Student]? { return arrayCollegeClass.first { $0.title == classTitle }?.students } 

    Call her like this:

     students(of: "9A", arrayCollegeClass: arrayCollegeClass) 
    • Thank! And how to get values ​​by key? For example, you need to get the names of students of the "9A" class. - maxMas
    • @maxMas So you have 1 class only. Add to the question at least one more class with students. - Roman Podymov
    • added another class - maxMas
    • @maxMas I updated my answer. - Roman Podymov