不能select pickerView的默认值

Can't select default value of pickerView

我有一个 pickerView,其中有很多主题。每个科目都是这样的class:

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

我这样设置我的 pickerView:

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
}

我想 select 特定主题的行,但我不能,因为 indexOf 它 "Cannot convert value of type 'String' to expected argument type '(subjects) throws -> Bool'" 在这行代码中:

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

有人可以帮助我吗?

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

而不是使用index(of:), the appropriate method for such a case is index(where:)

Returns the first index in which an element of the collection satisfies the given predicate.

这是适用的,因为你有一个自定义对象数组(subjects),如下:

if let index = MenuViewController.subjectsArray.index(where: { (subjectsObject) -> Bool in
    subjectsObject.nameSubject == "Matematica"
}) {
    print("found the desired index: \(index)")
    self.subjectsMenu.selectRow(index, inComponent: 0, animated: true)
}

补充说明:

  • 您的自定义名称 class 应该是 "Subject" 而不是 "subjects"。通常,classes 的名称是指单个对象,upper camel case.

  • 当比较字符串时:subjectsObject.nameSubject == "Matematica",最好是trim比较它的lower/upper案例版本吧,如下:

    subjectsObject.nameSubject.lowercased().trimmingCharacters(in: .whitespaces) == "Matematica".lowercased().trimmingCharacters(in: .whitespaces)