多种枚举类型列出所有情况 [英] Multiple enum types list all cases

查看:59
本文介绍了多种枚举类型列出所有情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法解决这个问题,也找不到任何答案,希望有人能指出我正确的方向.我有多个枚举.一些例子(我有很多,也有更复杂的枚举):

can't wrap my head around this and can't find any answers, hope someone could point me in the right direction. I have multiple enums. Some examples(i have a lot more and also more complex enums):

enum Fish: String, CaseIterable, Displayable {
    case goldfish
    case blueTang = "blue_tang"
    case shark
}

enum Tree: String, CaseIterable, Displayable {
    case coconut
    case pine
    case englishOak = "english_oak"
}

我想将这些显示在带有部分的列表中.我正在使用swiftUI,但这可能无关紧要.我想实现一个功能,仅通过提供Enum类型就可以为我提供视图.

I want to display those in a list with sections. I'm using swiftUI but that probably doesn't matter. I want to achieve a function that could provide me with a view just from giving an Enum type.

例如:

view(forType: Fish)

它看起来应该像这样:

func view(forType: Type) -> some View {
   VStack {
       Text(String(describing: Type.self))
       Type.allCases.forEach { case in
          ...
       }
    }
}

如果有人可以帮助我,如果有一种方法可以概括Enum类型,我将非常感谢!

If anyone could help me out on if there is a way how to generalize Enum types, I would be super thankful!

推荐答案

此处是可能解决方案的演示.使用Xcode 12.1/iOS 14.1编写

Here is a demo of possible solution. Prepared with Xcode 12.1 / iOS 14.1

enum Fish: String, CaseIterable {
    case goldfish
    case blueTang = "blue_tang"
    case shark
}

func view<T: CaseIterable & Hashable>(for type: T.Type) -> some View where T.AllCases: RandomAccessCollection {
    VStack(alignment: .leading) {
        Text(String(describing: type)).bold()
        ForEach(type.allCases, id: \.self) { item in
            Text(String(describing: item))
        }
    }
}

struct FishDemoView: View {
    var body: some View {
        view(for: Fish.self)
    }
}

这篇关于多种枚举类型列出所有情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆