gpt4 book ai didi

ios - 使用 Swift 从 Firebase 数据库创建过滤 TableView 的最佳方法是什么

转载 作者:行者123 更新时间:2023-11-30 13:14:28 24 4
gpt4 key购买 nike

我有一个表格 View ,显示从 Firebase 数据库中提取的歌曲标题,其中包含以下结构:

{
"songs" : {
"key1" : {
"lyrics" : "...",
"title" : "...",
"video" : "..."
}
}
}

如果我将 firebase 数据添加到名为 Song 的类中,那么我想我可以这样做:

var songs = [Song]()
var filteredSongs = [Song]()

let lower = searchBar.text!.lowercaseString
filteredSongs = songs.filter({$0.title.rangeOfString(lower) != nil})

但是,在遵循此问题的解决方案示例后,我没有成功做到这一点: convert FIRDataSnapshot to custom type

class Song: NSObject {
var title: String
var lyrics: String
var videoUrl: String
let ref: FIRDatabaseReference?

init(title: String, lyrics: String, videoUrl: String) {
self.title = title
self.lyrics = lyrics
self.videoUrl = videoUrl
self.ref = nil
}

init(snapshot: FIRDataSnapshot) {
title = snapshot.value!["title"] as! String
lyrics = snapshot.value!["lyrics"] as! String
videoUrl = snapshot.value!["video"] as! String
ref = snapshot.ref
}

convenience override init() {
self.init(title: "", lyrics: "", videoUrl: "")
}
}

有没有一种方法可以在不创建类的情况下添加过滤器?

最佳答案

最好将 JSON 转换为模型层中的结构/类,这样在 Controller 层中更容易使用。

除此之外,您可以执行以下操作:

json.value!["songs"].filter{ ($0.value!["title"] as! String).rangeOfString(lower) != nil}

正如你所看到的,它很丑陋。不要这样做。

关于ios - 使用 Swift 从 Firebase 数据库创建过滤 TableView 的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38380234/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com