我正在嘗試構建一個接受任何列舉大小寫作為其選擇的 SwiftUI,然后它會自動將其兄弟姐妹作為選項呈現。這是我開始的,但我很難克服泛型:
enum Option: String, CaseIterable, Identifiable, Equatable {
case abc
case def
case ghi
var id: Self { self }
}
struct CustomPicker<Sources>: View where Sources: RawRepresentable & CaseIterable & Identifiable, Sources.AllCases: RandomAccessCollection, Sources.RawValue == String {
@Binding var selection: Sources.AllCases.Element
var body: some View {
ScrollView(.horizontal) {
HStack(spacing: 8) {
ForEach(Sources.allCases) { item in
Text(item.rawValue)
}
}
.padding(.horizontal)
}
}
}
當我嘗試使用它時,我得到一個編譯錯誤Generic parameter 'Sources' could not be inferred::
enum Fruit: String, CaseIterable, Identifiable, Equatable {
case apple, banana, orange
}
struct ContentView: View {
@State private var selectedFruit: Fruit = .apple // Error here
var body: some View {
CustomPicker(selection: $selectedFruit) // Error here
}
}
如何使泛型正確以能夠處理任何 String/RawRepresentable 列舉并自動構建其兄弟姐妹?
uj5u.com熱心網友回復:
您的代碼離實作您期望的結果不遠了。一些評論:
- 您不需要要求
Sources符合Identifiable:它需要與Hashable一起使用ForEach,然后強制ForEach用作\.selfid。列舉的原始值是型別String(您需要它),使用\.self將始終有效。 Fruit不是Identifiable,也不需要是。- 主視圖正在傳遞,
Fruit但選擇器視圖需要一個型別Sources.AllCases.Element:它們不匹配。只需Sources在您的@Binding. - 記得更新
@Binding.
下面是一個作業示例:
struct ContentView: View {
@State private var selectedFruit: Fruit = .apple
@State private var selectedCar = Car.ferrari
var body: some View {
VStack {
CustomPicker(selection: $selectedFruit)
CustomPicker(selection: $selectedCar)
// Just for testing
Text("Eating one \(selectedFruit.rawValue) in a \(selectedCar.rawValue)")
.font(.largeTitle)
.padding()
}
}
}
// The Enum doesn't need to be Identifiable
enum Fruit: String, CaseIterable {
case apple, banana, orange
}
enum Car: String, CaseIterable {
case ferrari, porsche, jaguar, dacia
}
// Replace Identifiable with Hashable
struct CustomPicker<Sources>: View where Sources: RawRepresentable & CaseIterable & Hashable, Sources.AllCases: RandomAccessCollection, Sources.RawValue == String {
@Binding var selection: Sources // This is the right type
var body: some View {
ScrollView(.horizontal) {
HStack(spacing: 8) {
// Force the id as the item itself
ForEach(Sources.allCases, id: \.self) { item in
Text(item.rawValue)
// Somehow you need to update the @Binding
.onTapGesture {
selection = item
}
}
}
.padding(.horizontal)
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510442.html
標籤:迅速仿制药迅捷
