ios - 这里是否存在更好的解决方案来处理 Swift 中的这个 api 问题?

标签 ios json swift algorithm uitableview

我的原始 json 数据可能会误导您。键数组并不总是在同一索引处匹配其值。所以我重写了我的数据以反射(reflect)我的意图。

假设我们有一个 TableView 来显示带有它的 json 的歌曲:

{
    "albums": [
        {
            "title": "A",
            "id": "174172",
            "artistName": "Person X"
        },
        {
            "title": "B",
            "id": "19201827",
            "artistName": "Person Y"
        },
        {
            "title": "C",
            "id": "1927",
            "artistName": "Person Z"
        }
    ],
    "songs": [
        {
            "name": "Song A",
            "albumName": "A",
            "albumId": "174172",
            "duration": 180
        },
        {
            "name": "Song B",
            "albumName": "A",
            "albumId": "174172",
            "duration": 200
        },
        {
            "name": "Song C",
            "albumName": "B",
            "albumId": "19201827",
            "duration": 216
        },
        {
            "name": "Song D",
            "albumName": "C",
            "albumId": "1927",
            "duration": 216
        }
    ]
}

我的模式是这样的:

struct Album: Decodable {
    let title: String
    let id: String
    let artistName: String
}

struct Song: Decodable {
    let name: String
    let albumName: String
    let albumId: String
    let duration: Int
}

像这样的 View Controller 假代码:

class ViewController: UIViewController {
    var songs: [Song] = []
    var albums: [Album] = []

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return songs.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableview.dequeueReusableCell(withIdentifier: "SongCell", for: indexPath) as! SongCell
        let song = songs[indexPath.row]
        let album = albums.first { $0.id == song.albumId }
        cell.updateUI(withSong: song, album: album)
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let song = songs[indexPath.row]
        let album = albums.first { $0.id == song.albumId }
        pushDetailSongViewController(song, album)
    }

    func pushDetailSongViewController(_ song: Song, _ album: Album?) {
    }
}

当我们有太多带有专辑的歌曲时,let album = albums.first { $0.id == song.albumId } 会出现严重的性能问题。

那么我们应该在这里使用什么数据结构来处理更新性能?

最佳答案

在解析键和值之后,您可以将这两个数组组合成一个字典,然后让您的 TableView 的数据源成为该字典。

首先,使您的Song 结构符合Hashable 协议(protocol):

struct Song: Hashable {

为专辑和歌曲创建一个数组:

var albums: [Album] = []
var songs:  [Song]  = []

然后,将 songs 数组缩减为字典,如下所示:

let data = songs.reduce([Album: Song]()) { (result, song) -> [Album: Song] in
    guard let album = albums.first(where: { $0.id == song.albumID }) else { return result }
    return result.merging([album: song], uniquingKeysWith: { (first, _) in first })
}

我用两个演示数组对此进行了测试:

let albums = [Album(id: "1",     name: "one"), Album(id: "2",     name: "two"), Album(id: "3",     name: "three")]
let songs  = [Song(albumID: "1", name: "ONE"), Song(albumID: "2", name: "TWO"), Song(albumID: "3", name: "THREE")]

那些把数据变成:

[
    <Album id: "1", name: "one">  : <Song albumID: "1", name: "ONE">,
    <Album id: "2", name: "two">  : <Song albumID: "2", name: "TWO">,
    <Album id: "3", name: "three">: <Song albumID: "3", name: "THREE">
]

额外学分

如果你想要每张专辑的所有歌曲,你必须制作data [Album: [Song]]:

let data = albums.reduce([Album: [Song]]()) { (result, album) -> [Album: [Song]] in
    let _songs = songs.filter({ $0.albumID == album.id })
    guard !_songs.isEmpty else { return result }
    return result.merging([album: _songs], uniquingKeysWith: { (first, _) in first })
}

使用以下数组:

let albums = [Album(id: "1",     name: "one"), Album(id: "2",     name: "two"), Album(id: "3",     name: "three")]
let songs  = [Song(albumID: "1", name: "ONE"), Song(albumID: "2", name: "TWO"), Song(albumID: "3", name: "THREE"),
              Song(albumID: "1", name: "ONE-1"), Song(albumID: "1", name: "ONE-2"), Song(albumID: "3", name: "THREE-1")]

...你会得到:

[
    <Album name: three, id: 3>: [
        <Song name: THREE, albumID: 3>
        <Song name: THREE-1, albumID: 3>
    ], 
    <Album name: one, id: 1>: [
        <Song name: ONE, albumID: 1>, 
        <Song name: ONE-1, albumID: 1>, 
        <Song name: ONE-2, albumID: 1>
    ],
    <Album name: two, id: 2>: [
        <Song name: TWO, albumID: 2>
    ]
]

关于ios - 这里是否存在更好的解决方案来处理 Swift 中的这个 api 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53213304/

相关文章:

ios - 如何正确隐藏容器 View ?

iphone - 如何在 NSMangedObject 类别中的对多 NSSet 的索引处获取对象

jquery ajax调用返回对象,如何获取对象值

ios - Swift:获取用户的位置坐标作为纬度和经度?

swift - Swift 中的 CFSocket(四)

ios - UIPageControl 选择点并转到该页面

ios - 在 ScrollView SwiftUI 中添加时列表隐藏

ios - 将 UILabel 设置为隐藏

javascript - 对 JSON 数据进行编码以保留 json 格式

json - 应用程序输入规范: Drawing input data of method