【问题标题】:Declare and enum of a custom type (type has multiple raw value types within it)自定义类型的声明和枚举(类型中有多个原始值类型)
【发布时间】:2021-10-06 08:37:45
【问题描述】:

我有一个自定义结构类型,其中包含多个原始值类型(其中一些是自定义枚举):

struct Routes {

let routeTitle: String
let resortLocation: ResortLocations //<- Custom Enum
let distanceCategory: Distances //<- Custom Enum
let actualDistanceMiles: Double
let coordinates: [CLLocationCoordinate2D]

}

我将在模型中创建许多这些自定义“路线”类型,所以现在,我将它们存储在一个数组中。我要么通过常规索引引用它们

RouteArray.routes[0]

或他们的头衔:

for route in RouteArray {
  if route.routeTitle == "Route Name" {
     //use route
  }
}

但至少可以说,这两种方法似乎都效率低下。我想尝试设置一个枚举来代替:

enum RouteCatalog: Routes {
  case .routeName = //add in all the Routes information
}

但我遇到了一些错误:

'RouteCatalog' declares raw type 'Routes', but does not conform to RawRepresentable and conformance could not be synthesized

Raw type 'Routes' is not expressible by a string, integer, or floating-point literal

RawRepresentable conformance cannot be synthesized because raw type 'Routes' is not Equatable

我知道我可以使它符合 Equitable,并且我知道还有其他协议可以像在 this answer 中看到的那样,但考虑到我的数组中不同类型的数量,我想我只是对在这里做什么感到困惑。

另外,有没有更好的方法来做到这一点,还是应该像现在一样继续遍历数组?

感谢您的帮助!

【问题讨论】:

  • 这和SwiftUI没有任何关系
  • 抱歉.. 我在 SwiftUI 中构建它,这些是我拥有的自定义模型,旨在补充它。我现在将删除 SwiftUI 标记。
  • 我会说你在你想做的事情之间遗漏了一些事情没有意义和用例。
  • swiftPunk 对不起,我不明白。你是说我没有正确表达我的问题吗?

标签: arrays swift enums


【解决方案1】:

关联值

有一种方法可以用“关联值”做类似的事情。这不是原始值,但它做得很好。


enum ManyTypes {
    case integer(Int)
    case string(String)
    case anotherString(String)
    case customType(MyCustomType)
}

那么我们可以像这样使用多种类型的值:

func useManyTypes(_ type: ManyType) {
    switch type {
    case .integer(let value): print("Integer \(value)")
    case .string(let value): print("string" + value)
...

或者你可以更进一步,使用泛型。

enum Either<Left, Right> {
    case left(Left)
    case right(Right)
}

func returnIntOrString(_ string: Bool) -> Either<Int, String> {
    string ? .right("This is a string") : .left(0)
}

对于路由,您可以执行以下操作:


enum Route {
    case `sheet`(AnyView)
    case fullScreen(AnyView)
    case popOver(AnyView)
    case navigate(AnyView)
}


@State var nextView: AnyView!
@State var shouldTransitionWithSheet = false

func handle(route: Route) {
    switch route:
    case .sheet(let view):
        self.nextView = view
        self.shouldTransitionWithSheet = true
    ....
}

【讨论】:

    【解决方案2】:

    我建议使用字典而不是数组,并枚举你的路由标题(我假设这是结构的唯一标识符),用作字典中的键。

    enum RouteName {
        case routeName
        case …
    }
    

    更改属性声明

    let routeTitle: RouteName
    

    (我没有为枚举使用原始值,但如果您需要显示 routeTitle,请这样做)

    然后将您的路线保存在字典中

    Var routeCatalog: [RouteName: Routes]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2012-03-10
      • 1970-01-01
      相关资源
      最近更新 更多