Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

It seems cumbersome to have to list out each and every enum case like in the video.

Is there a better way to get the cases in the array.

https://teamtreehouse.com/library/concrete-types-and-property-lists-2

2 Answers

Michael Hulet
Michael Hulet
47,913 Points

When this video was recorded, that was the only way. You're right that this is super cumbersome and not very DRY. However, in Swift 4.2 (which came out in October, alongside iOS 12 and Xcode 10), the compiler can synthesize conformance to a new protocol called CaseIterable. By marking your enum as conforming to CaseIterable, it automatically gets a static property called allCases, which is an array containing all the cases in your enum. You can mark your conformance like this:

enum VendingSelection: CaseIterable { // Notice the conformance up here
    case soda
    case dietSoda
    case chips
    case cookie
    case sandwich
    case wrap
    case candyBar
    case popTart
    case water
    case fruitJuice
    case sportsDrink
    case gum
}

Later on when you need all the cases in the enum, you can get it like this:

let selection = VendingSelection.allCases

Thanks, I found it out when I asked but I put it inside an array by accident so it didn't work. "[VendingSelection.allCases]" was wrong.