Swift Basics - Enumerations

Enumerations
They can contain strings, characters, integers, or floating points.
To define an enumeration:
enum DaysOfWeek
{
  case Monday
  case Tuesday
  case Wednesday
}
OR
enum DaysOfWeek
{
  case Monday, Tuesday, Wednesday
 case Thursday, Friday, Saturday, Sunday
}

We can assign an enumeration value to a variable:
var today = DaysOfWeek.Saturday
We can use it with a switch case:
switch today
{
 case .Monday: print("Monday")
 case .Tuesday: print("Tuesday")
 default: print("Another day")
}

We can also populate enumerations with raw values

enum MyFavs: String
{
 case musicGenre = "Rock"
 case movie = "Shindler's List"
 case song = "Vindicated"
}
print("My fav song is : \(MyFavs.song.rawValue)")

We can assign numbers:
enum Months: Int 
{
 case January = 1
 case February= 2
}

print("The month January is month number \(Months.January.rawValue)")

We can assign more than one value to each case of an enumeration:
enum Food
{
 case Pizza(Double, Int, Int)
 case chickenRice(Double, Int)
}
var thisPizza = Food.Pizza(436.24, 1, 2)
switch thisPizza
{
  case .Pizza(let calories, let servings, let slices)
 print("Calories: \(calories)")


}

Comments

Popular posts from this blog

Setting up a playground

Go to another page