簡體   English   中英

使結構符合可識別崩潰應用程序

[英]Making struct conform to Identifiable crashes app

編輯:

  • 刪除了id: \.self
  • List中刪除.onDelete (編輯錯誤)
  • 刪除removeRows function
  • Note結構更改為僅 hash id

我正在 swiftUI 中制作一個返回筆記列表的應用程序。 我有一個結構note ,定義如下:

struct Note: Identifiable, Hashable {
    let id = UUID()
    var title: String
    var content: String

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
}

它符合Identifiable以便可以在List中選擇它,並且它符合Hashable以便它可以保存在Set中(供選擇)。

我認為(我認為)速度非常慢並最終崩潰的觀點如下:

struct SearchView: View {
    @State private var searchValue: String = ""
    @State private var searchResults: [Note] = [
        Note(title: "Hi", content: "whats up"),
        Note(title: "wassup", content: "hi")
    ]
    @State private var selectKeeper = Set<Note>()

    var body: some View {
        VStack(alignment: .leading) {
            SearchInputView(searchValue: $searchValue, searchResults: $searchResults)
            
            List(searchResults, selection: $selectKeeper) { note in
                Text(note.title )
            }
        }
    }
}

SearchInputView基本上只是一個視圖,它使用 combine 在每次按鍵時對文本字段的內容運行此 function:

func findIn(notes: [Note], pattern: String) -> [Note] {
    if pattern.isEmpty { return notes }
    
    var matchedNotes: [Note] = []
    
    for note in notes {
        let note = Note(title: note.title.uppercased(), content: note.content.uppercased())
        let pattern = pattern.uppercased()
        if note.title.contains(pattern) || note.content.contains(pattern) {
            matchedNotes.append(note)
        }
    }
    
    return matchedNotes
}

這一切過去都適用於ForEach循環和不符合IdentifiableNote結構,但現在無論出於何種原因,只要我在文本框中鍵入任何內容,應用程序就會崩潰。 我不知道為什么會這樣,而且我在分析器中看不到任何可能告訴我發生了什么的信息。 唯一的問題是,一旦我輸入,所有的使用率都會上升到 100%,並且應用程序會崩潰。 有任何想法嗎?

謝謝!

我發現我的問題是由於將findIn function 放在使用它的結構之外。 我完全不確定這是為什么,但是將它放在調用它的結構中會使它運行良好。 非常感謝所有在評論中提供有用建議的人!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM