【问题标题】:Returning a type based on a constraint, SwiftUI返回基于约束的类型,SwiftUI
【发布时间】:2020-10-05 10:35:41
【问题描述】:

我正在寻找一种可以根据枚举案例更改列表的方法,其中列表的源是 CaseIterable 枚举。例如:

enum TypeA: Int, CaseIterable {
    case one, two, three
}

enum TypeB: Int, CaseIterable {
    case a, b, c
}

我想写这样的东西:

enum PropChoice {
    case typeA, typeB
  
    func chosenEnumType<T: CaseIterable>() -> T {
        switch self {
            case .typeA:
                return TypeA.self as! T
            case .typeB:
                return TypeB.self as! T
        }
    }
}

然后像这样使用它:

let propType = PropChoice.typeA
let choices = propType.chosenEnumType.allCases()  \\\ Compiler error `Generic parameter T could not be inferred`

for choice in choices {
    print(choice.rawValue)
}

我收到如上所示的编译器错误。出于兴趣 - 我的用例是一个 SwiftUI 应用程序,用户可以在其中选择过滤器屏幕中的属性,并且我想在 Picker 中显示选项列表。

【问题讨论】:

  • 泛型并不是你真正需要的,因为你的返回类型不是泛型的,你只是希望能够返回几种不同的类型。解决方案是返回一个通用类型,在这种情况下是CaseIterable(或更准确地说,CaseIterable &amp;&amp; RawRepresentable,但是由于协议的associatedType 要求,它不能用作返回类型。所以您需要类型擦除才能返回符合 CaseIterable 的类型,但是,类型擦除 Caseiterable 并不是一项简单的任务(我不确定它是否可能)。

标签: swift generics enums


【解决方案1】:

建立some View 怎么样?够好吗?

enum PickerSelection {
  case typeA, typeB

  @ViewBuilder var forEach: some View {
    switch self {
    case .typeA:
      forEach(TypeA.self)
    case .typeB:
      forEach(TypeB.self)
    }
  }

  private func forEach<PickerSelection: CaseIterable & Identifiable>(
    _: PickerSelection.Type
  ) -> some DynamicViewContent
  where PickerSelection.AllCases: RandomAccessCollection {
    ForEach(PickerSelection.allCases) {
      Text(verbatim: "\($0)")
    }
  }
}
@State var selection = PickerSelection.typeA


Picker("Picker Selection", selection: $selection) {
  selection.forEach
}
extension Identifiable where Self: CaseIterable {
  var id: Self { self }
}

enum TypeA: Int, Identifiable, CaseIterable {
  case one, two, three
}

enum TypeB: Int, Identifiable, CaseIterable {
  case a, b, c
}

【讨论】:

    猜你喜欢
    • 2021-07-11
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 2021-11-10
    相关资源
    最近更新 更多