arrays - 快速搜索数组元素的最佳方式(性能)

标签 arrays swift search

我正在制作一个应用程序,我需要从一个可以随时更改的数组中获取数据。

例如数组:

posts_data: {
  ["id": 1, "text": "Hello"],
  ["id": 4, "text": "Good morning"],
  ["id": 6, "text": "Test"]
}

假设我需要更改post 1 的文本,但我不知道它的索引。然后过了一会儿我需要再次更改它,但帖子可能处于不同的位置。

func doSomeThing() :

if let index = posts_data.index(where: { $0.id == 1 }) {
    posts_data[index].text = "NEW TEXT"

    dispatchQueue.global().async {
    // Do something async, then I need to change the text again
    // But I need to search for the index again
    // Because the data source might changed meanwhile

        if let index2 = posts_data.index(where: { $0.id == 1 }) {
            posts_data[index2].text = "AGAIN"
            posts_data[index2].text = "AND AGAIN"
        }
    }

}

这有点过于复杂了。我想出了以下想法:将搜索放在自定义类中,如果通过 id 找到,则返回帖子:

class MainViewController : UIViewController {
    ...


    func doSomeThing(){
        if PostsClass.shared.getPost(id: 1) == nil {
           return // Just in case if not found
        }

        PostsClass.shared.getPost(id: 1).text = "NEW TEXT"
        dispatchQueue.global().async {
            // Bla bla

            PostsClass.shared.getPost(id: 1).text = "AGAIN"
            PostsClass.shared.getPost(id: 1).text = "AND AGAIN"

        }
    }
}


class PostsClass {
    static let shared = PostsClass()
    func getPost(id: Int) -> Post? {
        if let index = posts_data.index(where: { $0.id == id }) {
            return posts_data[index]
        }
        return nil
    }
}

这是更好还是一个坏主意?或者还有比这更简单的方法吗?

最佳答案

基本上,如果您尝试在数组中搜索,这是正确的。 但是,您可以使用不同的方法直接返回帖子:

return posts_data.first { $0.id == id }

关于arrays - 快速搜索数组元素的最佳方式(性能),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51696053/

相关文章:

java - 带有多个答案的 Arraylist Android Studio 测验应用程序

ios - 加载新数据时使缓存数据显示为响应式

ios - 在 Firebase-ios-swift 中创建和附加数组

iOS 在数组中搜索字符串并在丢失时添加它

javascript - 替换数组内容的简短方法

javascript 每次计算包含数组文字的表达式

arrays - 在 Twig 中循环两个数组

swift - iOS swift : Install and Unistall views programmatically

iphone - UISearchBar - "search results button"是做什么用的?

ios - 图片搜索引擎的使用