Multiple enum types list all cases

…衆ロ難τιáo~ 提交于 2021-01-28 05:13:47

问题


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"
}

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.

For example:

view(forType: Fish)

It should look something like:

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

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


回答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)
    }
}



回答2:


You have to declare your enum as CaseIterable in order to use allCases:

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

I'm not up to speed on SwiftUI/Combine yet, but here is how you would log all the cases in Swift:

Fish.allCases.forEach() {
        print($0)
}

That displays:

goldfish
blueTang
shark



回答3:


From what I can see in this article: https://www.hackingwithswift.com/example-code/language/how-to-list-all-cases-in-an-enum-using-caseiterable

You could conform enums to CaseIterable and do something like this

func view(forType: CaseIterable) -> some View

Or

func view<T: CaseIterable>(forType: T) -> some View

P.S.: I did not worked in swiftUI yet, so I'm not sure if generics works



来源:https://stackoverflow.com/questions/65182599/multiple-enum-types-list-all-cases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!