4

I have two enums and one associated enum. I need to get all the possible cases from enum A and enum B at once.

enum A {
    case a
    case b
    case c
}

enum B {
    case d
    case e
    case f
}

enum C {
    case first(A)
    case second(B)
}

extension C: CaseItratable {
 //How to implement?
}

Need a allCases method in enum C which returns all cases in enum A and all cases in enum B

2
  • Your question is a bit unclear. You want to simply get all A and B cases in a method in enum C? Commented Oct 22, 2019 at 7:55
  • yes I wan to get all possible cases in enum C Commented Oct 22, 2019 at 7:55

2 Answers 2

1

1. Conform enum A and enum B to CaseIterable protocol

enum A: CaseIterable {
    case a, b, c
}

enum B: CaseIterable {
    case d, e, f
}

2. Get all cases of enum A and enum B using allCases.

enum C {
    case first(A)
    case second(B)

    var casesOfA: [A] {
        return A.allCases //here...
    }

    var casesOfB: [B] {
        return B.allCases //here...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

It's more helpful if A and B are CaseIterable as well, then you can implement CaseIterable in C like this:

extension A: CaseIterable {}
extension B: CaseIterable {}

extension C: CaseIterable {

    static var allCases: [C] {
        return A.allCases.map(C.first) + B.allCases.map(C.second)
    }
}

3 Comments

You don't need the type alias, that is inferred automatically.
@Saranjith Which version of Swift are you using? It works fine on Swift 5.1.
@Saranjith What did you do?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.