Need help with School Database task: iterating over set + optionals

Hi all!

I got stucked with the task.
I need to write a method which iterates over Teachers and returns ones if conditions met.

Here is my code:

struct School {
  var name: String
  var teachers: [Teacher]

  func getTeacher(withID id: Int) -> [Teacher]? {
    for teacher in teachers {
      if == id {
        return teacher
      } else {
        return nil

I know I do something wrong, coz it gives me an error…but I cannot understand what and why :frowning:

error: SchoolDatabase.swift:20:16: error: cannot convert return expression of type ‘Teacher’ to return type ‘[Teacher]?’
return teacher

Can someone please explain what is wrong and help, please

1 Like

You ever get an answer to this?

@benstone91 I’m sorry for so many questions! However, I am stuck on this project as well. I am getting error messages re: my use of “FavoriteTeacher” in the print statements. I checked the project code and my code matches it.
SchoolDatabase.swift:31:52: error: use of unresolved identifier ‘favoriteteacher’
print(“('s favorite teacher is (”)

I’m actually not completely understanding how the code would know to print a favorite teacher’s name since the “FavoriteTeacher” property is attached to the student struct.

Thank you for your time on this!

The method getTeacher(withID:) expects to return an optional array of Teachers (type [Teacher]?). Your return statement only returns a single Teacher. You can either change the return type to Teacher? or change the return statement to return [teacher]

The code at the solution link (SchoolDatabase.swift · GitHub) seems to run fine for me.

You’ll need a Student to access their favoriteTeacherID. Is there a code snippet that you could share you’re having trouble with?

Wow, yeah when I run the full code it works perfectly. I was getting the errors as I added each print statement, but when I finished the full code, the errors went away. Thank you so much!!