in ios, mac, mobile

All about emum in swift

Enum or Enumerations are a special data types that enable us to group related types together and use them in a type-safe manner. enum in swift is not limited to an integer value as they are in another language, such as C or Java. enum in swift can have a string, character, integer, floating-point and much more type and define its actual value (raw value)

Defining enum in swift

enum Direction {
    case East
    case West
    case North
    case South
}

There is a shorter version also that lets us define multiple members in a single line separated by commas.

enum Direction {
    case East, West, North, South
}

Using enum

switch windDirection {
    case .East: print("East")
    case .West: print("West")
    case .North: print("North")
    case .South: print("South")
    default: ()
}

if windDirection == .East {
    print("East")
}

Value Type and Raw Value Enum

Enum can have Int, String, Double, Bool as a value type. For String and Int types, you can even omit the values and the Swift compiler will do the right thing:

// Mapping to Integer
enum Movement: Int {
    case Left = 0
    case Right = 1
    case Top = 2
    case Bottom = 3
}

// You can also map to strings
enum MacVersion: String {
    case MacOS8 
    case MacOS9 = "Mavrick"
    case MacOS10 = "Yosemite"
    case MacOS11 = "El Capitan"
    case MacOS12 = "Sierra"
}

// Or to floating point (also note the fancy unicode in enum cases)
enum Constants: Double {
    case π = 3.14159
    case e = 2.71828
    case φ = 1.61803398874
    case λ = 1.30357
}

Accessing and initializing enum

Enum values can be accessed and initialized by rawValue property. While initializing enum with rawValue, it is of type optional as not all value passed have mapped to enum member.

let move = Movement(rawValue: 1) //Left
let version = MacVersion(rawValue: "Mavrick") //MacOS9
let ver = MacVersion(rawValue: "Leopard")  // nil
 
print(MacVersion.MacOS10.rawValue) // Mavrick
print(MacVersion.MacOS8.rawValue)  // MacOS8

Associated Values

Swift enum can also have associated values which allow us to store additional information along with member values. This additional information can vary between the enum member.

enum Product {
    case Book(cost: Double,  pages: Int, author:String)
    case Mobile(cost: Double, osVersion: String)
}

let swiftBook = Product.Book(cost: 220.0,  pages: 500, author: "twanabashu")
let iPhone = Product.Mobile(cost: 98000,  osVersion: "10")



switch swiftBook {
case .Book(let cost, let pages, let author):
    print("cost:\(cost)  pages: \(pages) author: \(author)")
    
case .Mobile(let cost, let osVersion):
    print("cost: \(cost)osVersion:\(osVersion)")
}

Method and Properties

enum in swift can have method and properties like structure and class

enum Device {
    case iPad, iPhone, AppleTV, AppleWatch
    var year: Int {
        switch self {
        case .iPhone: return 2007
        case .iPad: return 2010
        default:()
        }
        return 0
    }

    static func from(term: String) -> Device? {
        if term == "iWatch" {
            return .AppleWatch
        }
        return nil
    }
    

    func introduced() -> String {
        switch self {
        case .AppleTV: return "\(self) was introduced 2006"
        case .iPhone: return "\(self) was introduced 2007"
        case .iPad: return "\(self) was introduced 2010"
        case .AppleWatch: return "\(self) was introduced 2014"
        }
    }
}
print (Device.iPhone.introduced())  //iPhone was introduced 2007
print (Device.iPhone.year) //2007
print(Device.from(term: "iWatch")!) //AppleWatch

Mutating Methods

Methods can be declared mutating. They’re then allowed to change the case of the underlying self-parameter.

enum GameLevel {
    case Level1, Level2, Level3
    
    mutating func upgrade(){
        switch self {
        case .Level1:
            self = .Level2
        case .Level2:
            self = .Level3
        case .Level3:
            self = .Level3
        default:()
        }
    }
}

var level = GameLevel.Level1  // Level1
level.upgrade()   //Level2

	

Generic Enums

Enums can also be defined over generic parameters. You’d use them to adapt the associated values of an enum.

struct Dog {
    var name: String
}

struct Human {
    var name: String
}

enum Avatar<T, U> {
    case Dog(T)
    case Human(U)
    
}

let dog = Dog(name: "tiger")
let human = Human(name: "ravi")

let mammal = Avatar<Dog, Human>.Dog(dog)
switch mammal {
case .Dog(let dog): print(dog.name)
case .Human(let human): print(human.name)
default:()
}

enum as Identifiers and constants

Enums can be used to map reuse identifiers or storyboard identifiers. Similarly, enum can be used to hold constant. In normal ways, you cannot have more than one parameter with the same name in one application, but with enum we can achieve this and this will make lot easier to manage constant in application

enum Constant {
    enum Identifier {
        static let identifier1 = "identifier1"
        static let identifier2 = "identifier2"
        static let identifier3 = "identifier3"
    }
    enum Production {
        static let baseURL = "http://production.com"
    }
    enum Uat {
        static let baseURL = "http://uat.com"
    }
}

let viewid = Constant.Identifier.identifier1
#if DEBUG
    let baseUrl = Constant.Uat.baseURL
#else
    let baseUrl = Constant.Production.baseURL
#endif

Looking at the advance use of enum, it is very similar to a struct in swift. It can have a parameter, methods. One should know the difference between enum and swift here and when to use.

  • enums are initialized by one of a finite number of cases, are completely defined by their case, and should always be valid instances of that case when instantiated
  • structs should be used when there is not a finite number of valid instances (e.g. enum cases) and the struct also does not form a complete definition of an object, but rather an attribute of an object

Write a Comment

Comment

Webmentions

  • можно ли купить виагру в аптеке

    legitimate canadian mail order pharmacies https://viagravonline.com/

    You made your position extremely well!.

  • гдз по алгебре макарычев

    canada drug http://rennchonddust.webcindario.com

    You actually said that perfectly.

  • гдз по русскому 6 класс

    canadian pharmacies that are legit http://flordylua.webcindario.com

    Effectively spoken indeed! !

  • гдз тростенцова

    canadian pharmacies that are legit http://formlawhols.webcindario.com

    You have made your stand very nicely!.

  • алимов гдз

    online canadian pharmacies http://laufreerax.webcindario.com

    Appreciate it. An abundance of info!

  • гдз по русскому 7 класс

    pharmacy http://swermapi.webcindario.com

    Seriously many of excellent material.

  • гдз 7 класс

    best canadian mail order pharmacies http://detrimo.webcindario.com

    Thanks! A good amount of knowledge!

  • гдз по алгебре мордкович

    legitimate canadian mail order pharmacies http://ginnfatert.webcindario.com

    Regards! A good amount of stuff.

  • гдз по алгебре 9 макарычев

    canada drugs http://wormiki.webcindario.com

    Thank you, A good amount of posts!

  • meds online without doctor prescription

    prescription drugs without prior prescription http://withoutadoctor.viagraiy.com/

    Very good tips. With thanks.

  • pharmacies

    prescription drugs without prior prescription http://canadianorderpharmacy.com/

    Cheers. Quite a lot of tips!