Enums

Enums are used to define a collection of similar items. It allows the declaration to be in one place. This makes updating code easier and reduces the chance of error, misspelling variable names for example.

The enum can be declared in a new plain Swift file. In the Swift file the enum and it possible values is declared. For example the enum Animal can be defined as a String.

import Foundation

enum Animal: String
{
    case Cat = "Cat"
    case Dog = "Dog"
    case Horse = "Horse"
    case Cow = "Cow"
    case Nothing = "Nothing"
}
This is a rather trivial example but autocomplete means a reduced chance of spelling mistakes. The enum can be used in the application code as Animal.xxx as a string variable. For example
var animal1: String = Animal.Cat
var animal2: string = Animal.Dog

Index


Comments, Corrections, Suggestions: David Bourne (david@boomer.org)
My iOS and tvOS Apps and iBooks