如何从JSON筛选多个值并将结果附加到TableView Swift4

时间:2018-08-21 16:14:38

标签: swift uitableview filter swift4

我正在尝试找到一种解决方案,该解决方案如何同时过滤本地JSON文件中的多个值。值来自UserDefaults(我有一个viewController,其中包含一些按钮,当按钮处于活动状态时,它将值保存到UserDefaults。这基本上意味着用户的兴趣)。可能会有不止一种兴趣。 JSON如下所示:

{
    "article" : [
        {
            "title" : "Basketball",
            "subtitle" : "NBA",
            "interest" : "sports"
        },
        {
            "title" : "Africa",
            "subtitle" : "Sahara",
            "interest" : "travel"
        },
        {
            "title" : "Space",
            "subtitle" : "Satelitte",
            "interest" : "science"
        }
    ]
}

我需要过滤“兴趣”键,如果它与要过滤的值匹配(来自UserDefaults),然后将这些文章附加到tableView。这应该在加载表视图之前完成。来自userDefaults的变量:

let sportsInterest = UserDefaults.standard.object(forKey: "Sports") as! String // contains "sports"
let travelInterest = UserDefaults.standard.object(forKey: "Travel") as! String // contains "travel"

模型如下:

class Articles: Codable {
    let article: [Article]

    init(article: [Article]) {
        self.article = article
    }
}

class Article: Codable{
    let title: String
    let subtitle: String
    let interest: String

    init(title: String, subtitle: String, interest: String) {
        self.title = title
        self.subtitle = subtitle
        self.interest = interest
    }
}

我正在以这种方式解析JSON:

private var articles = [Article]()
var fileName: String = "Tasks"

func downloadJSON() {
    let url = Bundle.main.url(forResource: fileName, withExtension: "json")!

    do {
        let data = try Data(contentsOf: url)
        let articleList = try JSONDecoder().decode(Articles.self, from: data)

        self.articles = articleList.article

        DispatchQueue.main.async {
            self.articlesTV.reloadData()
        }
    } catch {
        print("Error occured during Parsing", error)
    }
}

1 个答案:

答案 0 :(得分:1)

filter是正确的关键字。

let sportsArticles = articles.filter { $0.interest == sportsInterest }

或获得更多条件

let criteria = [travelInterest, sportsInterest]
let filteredArticles = articles.filter { criteria.contains($0.interest) }

如果应该在加载数据后立即过滤文章

let articleList = try JSONDecoder().decode(Articles.self, from: data)
self.articles = articleList.article.filter { criteria.contains($0.interest) }

可能是 未知 ,但是如果该类采用Codable,则这些类中的初始化程序是多余的。