我正在使用 swift 包 [ Defaults][1] 來管理我的應用程式中的首選項串列。其中一個屬性是我使用的結構陣列@Default(.list) var list。在 Swift UI 中,我在此串列上回圈以編輯各種元素。
@Default(.list) var list;
ForEach($list, id: \.wrappedValue.id) { element in
...
}
它作業正常,并且按預期作業。
我的問題是我需要過濾這個串列。我正在使用$list.filter(...),但我收到警告Conformance of 'Binding<Value>' to 'Sequence' is only available in MacOS 12.0。
不幸的是,我的應用程式需要在 MacOS 11.x 上運行。
我真的不明白警告的含義以及如何調整我的代碼以使其適用于 MacOS 11.x。
謝謝!
- 更新 -
struct Stock: Codable, Identifiable, DefaultsSerializable {
var id: String
var currency: String = "USD"
}
extension Defaults.Keys {
static let stocks = Key<[Stock]>("stocks", default: [])
}
struct StocksView: View {
@Default(.stocks) var stocks
func filterStocks(stock: Stock) -> Bool
{
return stock.currency == "USD"
}
var body: some View {
ForEach($stocks.filter(filterStocks, id: \.wrappedValue.id) { stock in
....
}
}
}
extension Binding where Value == [Stock] {//where String is your type
func filter(_ condition: @escaping (Stock) -> Bool) -> Binding<Value> {//where String is your type
return Binding {
return wrappedValue.filter({condition($0)})
} set: { newValue in
wrappedValue = newValue
}
}
}
[1]: https://github.com/sindresorhus/Defaults
uj5u.com熱心網友回復:
當您使用$list.filter您的未過濾list時,您正在過濾Binding<[List]>不符合協議序列的過濾器。
將此擴展添加到您的專案中,看看它是否有效
extension Binding where Value == [String] {//where String is your type
func filterB(_ condition: @escaping (String) -> Bool) -> Binding<Value> {//where String is your type
return Binding {
return wrappedValue.filter({condition($0)})
} set: { newValue in
wrappedValue = newValue
}
}
}
編輯:Binding在一個ForEach要求SwiftUI 3
但是,您可以傳遞普通陣列,并在需要時Binding使用此函式:
extension Stock {
func binding(_ array: Binding<[Stock]>) -> Binding<Stock> {
Binding {
self
} set: { newValue in
guard let index = array.wrappedValue.firstIndex(where: {$0.id == newValue.id}) else {return}
array.wrappedValue[index] = newValue
}
}
}
所以你的代碼看起來像這樣:
ForEach(stocks.filter(filterStocks), id: \.id) { stock in
....
SomeViewRequiringBinding(value: stock.binding(stocks))
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/490680.html
上一篇:如何將字串回傳到主函式?
