Search code examples
swiftuipickerview

Can't select default value of pickerView


I have a pickerView in which there are a lot of subjects. Every subject is a class like this:

class subjects {
    var idSubject: String = "";
    var nameSubject: String = "";
    var notesSubject: String = "";
    var colorSubject: String = "";

    init(subjectId: String, subjectName: String, subjectNotes: String, subjectColor: String) {
        idSubject = subjectId
        nameSubject = subjectName
        notesSubject = subjectNotes
        colorSubject = subjectColor
    }

    func printSubject(){
        print(idSubject," - ",nameSubject," - ",notesSubject," - ",colorSubject)
    } 
}

I set my pickerView in this way:

public func numberOfComponents(in pickerView: UIPickerView) -> Int{
    return 1
}

public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
    return MenuViewController.subjectsArray.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    self.view.endEditing(true)
    return MenuViewController.subjectsArray[row].nameSubject
}

I want to select the row of a particular subject, but I can't because with indexOf it "Cannot convert value of type 'String' to expected argument type '(subjects) throws -> Bool'" in this lines of code:

if let index = MenuViewController.subjectsArray.indexOf("Matematica") {
    self.subjectsMenu.selectRow(index, inComponent: 0, animated: true)
}

Can someone help me?


Solution

  • if let index = MenuViewController.subjectsArray.index(where: {
        $0.nameSubject == "Matematica"
    }) {
        self.subjectsMenu.selectRow(index, inComponent: 0, animated: true)
    }