Programming in Swift: Functions & Types

Jan 4 2022 · Swift 5.5, iOS 15, Xcode 13

Part 3: Enumerations

21. Enumerations

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 20. Introduction Next episode: 22. Challenge: Enumerations

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 21. Enumerations

Update Notes: This course was originally recorded in 2019. It has been reviewed and all content and materials updated as of October 2021.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

So, when I say “a specific set of related, discrete values.” What do I mean? Some commons examples are cardinal directions, colors, or card suits. State machines, like a traffic light, are also a great use case.

enum Month {
  
}
case january
case february
case january, february, march, april, may, june, july, august, september, october, november, december
let month = Month.october
let month: Month = Month.october
let month: Month = .october
enum Month😺: Int🛑 {
case january😺 = 1🛑,
func monthsUntilJingleBells(from month: Month) -> Int 
}
  Month.december.rawValue - month.rawValue
}
monthsUntilJingleBells(from: .november)
let rawMonth = Month(rawValue: 3)

String Raw Values

Let’s set up one more Enumeration! This one will be for seasons

enum Season
enum Season: String {

}
enum Season: String {
  case winter
  case spring
  case summer 
  case autumn
}
enum Season: String {
  😺/// ☃️
  case winter
  
  😺/// 🌸
  case spring
  
  😺/// 😎
  case summer
  
  😺/// 🍂
  case autumn
}
Season.
Season.winter
Season.winter😺.rawValue

CaseIterable

Sometimes you might want to do something like figure out how many cases an enumeration has, or iterate through those cases and do something with each of them. You can absolutely do that, you just need to make your enumeration conform to the CaseIterable protocol.

enum Season: String😺, CaseIterable🛑 {
Season.allCases
Season.allCases😺.filter {
  $0.rawValue.first == "s"
}🛑