如何从 NSObject 数组中过滤项目

How to filter item from NSObject Array

下面是我的 2 个对象

肌肉

struct MuscleListObject {
    var strMuscleName: String = ""
    var arrMuscleExercise: [MuscleExerciseListObject] = []
}

练习对象

struct MuscleExerciseListObject {
    var strExerciseName: String  = ""
}

我知道 Muscle wise 过滤器,但我想搜索 item exercise wise。我怎样才能做到这一点?请指导我。

arrSearchedMuscle = self.arrExercise.filter({ objMuscle in
    if let name = objMuscle.strMuscleName as? String, let query = searchBar.text {
        return name.range(of: query, options: [.caseInsensitive, .diacriticInsensitive]) != nil
    }
    return false
})

编辑

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchText.count == 0 {
            isSearching = false
            arrSearchedMuscle = arrExercise
        }
        else {
            isSearching = true

            let query = searchText
            arrSearchedMuscle = arrExercise.compactMap { category -> MuscleListObject? in
                if category.strMuscleName.range(of: query, options: [.caseInsensitive]) != nil {
                    return category
                } else {
                    arrSearchedExercise = category.arrMuscleExercise.filter({ [=13=].strExerciseName.range(of: query, options: [.caseInsensitive]) != nil  })
                    if arrSearchedExercise.isEmpty {
                        return nil
                    } else {
                        let newCategory = category
                        newCategory.arrMuscleExercise = arrSearchedExercise
                        return newCategory
                    }
                }
            }
            print(arrExercise)
            print(arrSearchedMuscle)
        }
        self.tblVWExercise.reloadData()
    }

请指导我有关过滤器调用的信息。 提前致谢

如果肌肉标题包含搜索查询 return 整个肌肉 object。如果不使用搜索查询和 return 更新肌肉 object 过滤锻炼 objects。如果特定肌肉 object 不包含搜索查询 return nil

let query = "band"
arrSearchedMuscle = arrExercise.compactMap { category -> MuscleListObject? in
    if category.strMuscleName.range(of: query, options: [.caseInsensitive]) != nil {
        return category
    } else {
        let filteredItems = category.arrMuscleExercise.filter({ [=10=].strExerciseName.range(of: query, options: [.caseInsensitive]) != nil  })
        if filteredItems.isEmpty {
            return nil
        } else {
            var newCategory = category
            newCategory.arrMuscleExercise = filteredItems
            return newCategory
        }
    }
}
print(arrExercise)
print(arrSearchedMuscle)