swift - 如何从 JSON 中过滤多个值并将结果附加到 TableView Swift 4

标签 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"
        }
    ]
}

I need to filter the "interest" key and if it matches the values that are being filtered (comes from UserDefaults), then append those articles to the tableView. This should be done before the tableview loads. The variables from 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)
    }
}

最佳答案

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,则类中的初始化器是多余的 😉。

关于swift - 如何从 JSON 中过滤多个值并将结果附加到 TableView Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51952831/

相关文章:

javascript - AngularJS 在某些字段中过滤 "OR"条件

javascript - Angular JS通过逻辑AND过滤,使用多个术语

ios - ScrollView 不向右滚动

swift - Firebase 2.0 - 从 FIRDataSnapshot 读取数据不起作用

swift - 在 UITableView 重新加载时从 SDWebImage 设置图像

ios - UIVisualEffectView 和 UITableView

c++ - 稳定红外距离传感器输出值

swift - 在swift 4中获取字体属性

ios - 如何使用台风快速注入(inject)委托(delegate)?

ios - 为什么我们不能在 UITableView、Objective C 上检测到 UITouch 逻辑