UISearchController在Struct中搜索struct数组

问题描述 投票:1回答:1

我在课程列表中有2个结构。

struct Course : Decodable {
let CourseName : String;
let EntryRequirements : String;
}

struct  WebsiteDescription : Decodable {
let FullProgramName :String
let ProgramName : String;
let Courses : [Course]
}

这些结构加载了JSON

我已经实现了一个UISearchController来实际搜索课程名称。

我不知道如何从WebsiteDescription中引用包含课程名称的Struct课程。

我过去用于包含WebsiteDescription的数组

  var allCourses = [WebsiteDescription]()
  var filteredCourses = [WebsiteDescription]()

我试图用这种方法过滤它

func updateSearchResults(for searchController: UISearchController) {
    if searchController.searchBar.text! == "" {
        filteredCourses = allCourses
        acTableView.reloadData()
    } else {
        filteredCourses = allCourses.filter { $0.ProgramName.lowercased().contains(searchController.searchBar.text!.lowercased()) }



    }  
    self.acTableView.reloadData();
}

它过滤了一般程序名称,但我实际上想要使用struct Course中的CourseName进行过滤。

先感谢您。

This is what I currently get

当我搜索指导时,整个ShortCourses部分出现时只会出现'指导'。

指导是课程名称

ios swift uisearchbar uisearchcontroller
1个回答
1
投票

替换此行

allCourses.filter { $0.ProgramName.lowercased().contains(searchController.searchBar.text!.lowercased())

有了这个

allCourses.filter {
             !$0.Courses.filter{$0.CourseName.localizedCaseInsensitiveContains(searchController.searchBar.text!)}.isEmpty
        }

它将根据你在CourseName结构中的Course给出结果。

编辑:它会给你ArrayCourse

allCourses.flatMap{$0.Courses.filter{$0.CourseName.localizedCaseInsensitiveContains(searchController.searchBar.text!)}}
© www.soinside.com 2019 - 2024. All rights reserved.