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

  • pharmacy canada

    list of reputable canadian pharmacies https://ecoutegli.bandcamp.com/track/pharmacies-shipping-to-usa

    Regards. Terrific stuff.

  • canadian online pharmacies

    trust pharmacy canada https://solorider.com/forums/users/canadian-pharmaceuticals/

    You revealed that really well!

  • global pharmacy canada

    pharmacy https://bitcoinblack.net/community/prescription-drugs-from-canada/info/

    Excellent info. Many thanks.

  • canadian pharmaceuticals

    canadian rx https://rabbitroom.com/members/canadianpharmaceuticalsonlinewithnoprescription/profile/

    Beneficial knowledge. Thank you!

  • canada medication

    canada pharmacy https://the-dots.com/projects/drugstore-online-shopping-889086/

    This is nicely put. !

  • canada pharmacies online prescriptions

    online canadian pharmacies https://cialispharmacy.cgsociety.org/profile

    Regards. I appreciate this!

  • canada pharmacies

    canadian online pharmacies https://haikudeck.com/presentations/cheapprescriptiondrugs

    Awesome material. Many thanks!

  • best canadian mail order pharmacies

    canada pharmacy https://www.gamespace.com/members/canadianprescriptionsonline/

    Seriously all kinds of awesome info.

  • safe canadian online pharmacies

    no 1 canadian pharcharmy online http://canadianpharmaceuticalsonlinee.iwopop.com/

    Perfectly spoken certainly! .

  • drugs for sale

    canadian pharcharmy online https://linktr.ee/canadianpharmaceuticalsonlineu

    You actually expressed it effectively!

  • canada drug

    canada pharmacies online prescriptions https://halttancentnin.livejournal.com/301.html

    Excellent posts. Thanks a lot!

  • canadian pharcharmy online

    canada drug pharmacy https://canadianpharmaceuticalsonline.myjournal.jp/archives/18054504.html

    Really tons of beneficial info.

  • best canadian mail order pharmacies

    canadian pharcharmy online https://canadianpharmaceuticalsonline.publog.jp/archives/16846649.html

    Really a lot of beneficial tips.

  • erectile pills canada

    erectile dysfunction medications https://challonge.com/afersparun

    Thanks a lot, Helpful information!

  • canadian pharmacies that are legit

    canada pharmacies https://rentry.co/canadianpharmaceuticalsonline

    You have made your point!

  • canadian rx

    canadian pharmacies mail order https://jemi.so/canadian-pharmacies-shipping-to-usa

    With thanks, Loads of facts!

  • canadian pharmacies mail order

    highest rated canadian pharmacies https://www.podcasts.com/canadian-pharmacies-shipping-to-usa

    You reported that fantastically.

  • stromectol for sale online

    buy ivermectin online https://telegra.ph/Order-Stromectol-over-the-counter-10-29

    Reliable posts. Many thanks!

  • stromectol dosage table

    stromectol doses https://buystromectol.livejournal.com/421.html

    You explained that well.

  • stromectol stock

    facts stromectol https://orderstromectoloverthecounter.mystrikingly.com/

    Wonderful forum posts. Kudos.

  • stromectol mites

    generic stromectol https://aleserme.estranky.sk/clanky/stromectol-espana.html

    Useful advice. Thank you.

  • stromectol buy online

    stromectol buy https://pinshape.com/users/2491694-buy-stromectol-fitndance

    With thanks. Loads of material.

  • stromectol pills

    stromectol treatment scabies https://aoc.stamford.edu/profile/cliclecnotes/

    Good info, Kudos!

  • canada pharmacy

    canadian drug https://feeds.feedburner.com/bing/stromectolnoprescription

    Truly loads of awesome tips.

  • canada online pharmacies

    canadian rx https://feeds.feedburner.com/bing/Canadian-pharmaceuticals-online

    Appreciate it! A good amount of data!

  • canadian government approved pharmacies

    best canadian mail order pharmacies https://www.giantbomb.com/profile/canadapharmacy/blog/canadian-pharmaceuticals-online/265652/

    Cheers, Ample information.

  • generic stromectol

    stromectol in india https://sanangelolive.com/members/girsagerea

    Nicely put. Appreciate it.

  • canada pharmacies

    trust pharmacy canada https://network.myscrs.org/profile/422020/0

    Thanks a lot, Wonderful information.

  • prescription drugs without prior prescription

    canada pharmacies online https://moaamein.nacda.com/profile/422018/0

    You said it very well..

  • stromectol reviews

    stromectol canada https://inflavnena.zombeek.cz/

    Thank you! I like it.

  • reaction au stromectol

    ivermectin tablets https://order-stromectol-over-the-counter.estranky.cz/clanky/order-stromectol-over-the-counter.html

    You expressed it fantastically.

  • northwest pharmacies

    canada drug https://bursuppsligme.bandcamp.com/releases

    Good data. Regards.

  • facts stromectol

    stromectol purchase https://aoc.stamford.edu/profile/Stromectol/

    Very good knowledge. Appreciate it!

  • canadian pharmacies that ship to us

    legitimate canadian mail order pharmacies https://canadajobscenter.com/author/canadianpharmaceuticalsonline/

    Nicely put. Appreciate it!

  • canada pharmacies online

    prescriptions from canada without https://www.scoop.it/topic/canadian-pharmaceuticals-online

    Thanks a lot, I like it.

  • canadian mail order pharmacies

    trust pharmacy canada https://pinshape.com/users/2441403-canadian-pharmaceuticals-online

    With thanks! Lots of knowledge.

  • challonge.comencanadianpharmaciesshippingtousa

    online prescriptions without a doctor https://challonge.com/en/canadianpharmaciesshippingtousa

    Thanks! An abundance of advice!

  • buyviagraonline.nethouse.ru

    online prescriptions without a doctor https://buyviagraonline.nethouse.ru/

    Terrific content. Thank you.

  • https://buyviagraonline.fo.team/

    online prescriptions without a doctor https://buyviagraonline.fo.team/

    Many thanks, Numerous postings.

  • buyviagraonline.flazio.com

    online prescriptions without a doctor https://buyviagraonline.flazio.com/

    Nicely put. Thanks!

  • canada rx

    prescription drugs without prior prescription https://linktr.ee/onlinepharmacies

    You expressed that wonderfully!

  • global pharmacy canada

    pharmacy https://kawers.micro.blog/

    Awesome information. Cheers!

  • canadian pharmacies that are legit

    northwest pharmacies https://hub.docker.com/r/pharmacies/online

    Helpful material. Thanks!

  • https://site273035107.fo.team/

    medication without a doctors prescription https://site273035107.fo.team/

    You’ve made your point pretty clearly..

  • canadian pharmacies online prescriptions

    Northwest Pharmacy https://womed7.wixsite.com/pharmacy-online/post/new-ideas-into-canada-pharmacies-never-before-revealed

    Position nicely used!!

  • canadian prescription drugstore

    canadian discount pharmacies https://kewertyn.wordpress.com/2022/04/27/expect-more-virtual-house-calls-out-of-your-doctor-thanks-to-telehealth-revolution/

    You actually expressed this wonderfully!

  • https://ghswed.wordpress.com/2022/04/27/he-final-word-information-to-online-pharmacies/

    online prescriptions without a doctor https://ghswed.wordpress.com/2022/04/27/he-final-word-information-to-online-pharmacies/

    Kudos, I enjoy it.

  • canada drugs

    online canadian pharmacies https://site128620615.fo.team/

    Great forum posts. With thanks.

  • seketu.gonevis.comhigh-10-tips-with-order-medicine-online-1

    medication without a doctors prescription https://seketu.gonevis.com/high-10-tips-with-order-medicine-online-1/

    Superb data. Thanks a lot!

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

    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!