簡體   English   中英

SwiftUI 用於字典條目的結構

[英]SwiftUI Struct for Dictionary entry

經過幾年的開發,我決定使用 SwiftUI 重新啟動我的項目,以盡可能地證明未來。

在我當前的項目中,我將數據保存在幾個.CSV 中,然后將其處理成字典,然后使用從用戶輸入以編程方式生成的鍵數組在屏幕上創建條目列表。

我見過的 SwiftUI 的所有示例都使用 JSON。 但是,這些文件的結構與字典數組相同。 我的問題是; 是否可以創建一個字典條目的結構來傳遞一個 forEach 觀察鍵數組(字典中的數據永遠不會改變,我不打算迭代或查看字典)。

我的主要目標是盡可能多地重用,但我願意改變我必須充分利用 SwiftUI 的東西。 顯然,如果我改變存儲數據的方式,幾乎所有東西都將毫無用處。 如果將我的數據轉換為 JSON 或什至開始使用 CoreData 之類的東西有真正的好處,我會的。

如果我理解正確,您正在尋找

  1. 接受一些用戶輸入
  2. 將其轉換為與您的數據字典對應的鍵
  3. 將匹配鍵的數據提取到某個結構中
  4. 使用 SwiftUI 顯示這些結構的列表

這是這些步驟的簡單實現。

import SwiftUI

// A dictionary containing your data
let data: [String: Int] = [
    "apples": 5,
    "bananas": 3,
    "cherries": 12
]

// A struct representing a match from your data
struct Item {
    var name: String
    var quantity: Int
}

// A view that displays the contents of your struct
struct RowView: View {
    var item: Item

    var body: some View {
        Text("\(item.quantity) \(item.name)")
    }
}

struct ContentView: View {
    @State private var searchText: String = ""

    func items(matching search: String) -> [Item] {
        // 2 - split the user input into individual keys
        let split = search.split(separator: " ", omittingEmptySubsequences: true).map { $0.lowercased() }
        // 3 - turn any matching keys/values in your dictionary to a view model
        return split.compactMap { name in
            guard let quantity = data[name] else { return nil }
            return Item(name: name, quantity: quantity)
        }
    }

    var body: some View {
        VStack {
            // 1 - get user input
            TextField("Search", text: $searchText)
                .padding()
            // 4 - display the matching values using ForEach (note that the id: \.name is important)
            List {
                ForEach(items(matching: searchText), id: \.name) { item in
                    RowView(item: item)
                }
            }
        }
    }
}

您會看到,當您在文本字段中鍵入時,如果您輸入任何字符串“apples”、“bananas”或“cherries”,相應的行將彈出到您的列表中。

根據列表的大小以及對用戶搜索查詢執行的驗證類型,您可能需要更加小心地以有效的方式進行過濾/搜索(例如,使用組合來僅拆分和搜索在用戶停止輸入后)。

暫無
暫無

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

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