The Enum Basics

    Let’s Review

    1. Basic Enumerations
    2. Enumerations that have Raw Values
    3. Enumerations that have Associated Values

    Create an enum called . It contains 4 cases.

    You define multiple cases in a single line

    1. enum Planet {
    2. case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
    3. }

    To initialize, you choose one of the cases.

    1. let earth = Planet.earth // init

    You may run through a switch statement to identify the enum type.

    1. switch earth {
    2. case .earth:
    3. default:
    4. print("Not a safe place for me")
    5. }
    6. // "Mostly safe"
    • Int
    • Float
    • String
    • Bool

    Raw Value: String

    1. enum Days: Int {
    2. case mon, tue, wed, thu, fri = 10, sat, sun
    3. }
    4. let myDay = Days.fri.rawValue
    5. print(myDay) // 10

    Initialization from Raw Value

    You may create an enum object using a raw value. it may fail. Therefore, the returned object may be nil.

    1. let possibleeDay = Days(rawValue: 10) // returns optional
    2. print(possibleeDay!)

    You may combine with a switch statement.

    1. if let someDay = Days(rawValue: 3) {
    2. switch someDay {
    3. case .sat, .sun:
    4. print("Weekends!!")
    5. print("Weekdays!")
    6. }
    7. } else {
    8. print("No such day exists")
    9. }

    Each case may contain value along with it.

    Validation

    Determine if the instance is Barcode.qrCode using an else-if statement. The process is similar to implicit unwrapping.

    1. if case let Barcode.qrCode(value) = qrCode {
    2. print("This is a qrcode")
    3. }

    You may capture the associated value of the instance, qrCode using case let. You’ve named the captured value as value.

    1. if case let Barcode.upc(numberSystem, manufacturer, product, check) = upcCode {
    2. print("numbersystem:", numberSystem)
    3. print("manufaturer:",manufacturer)
    4. print("product:",product)
    5. print("check:",check)
    6. }

    Instead of checking each enum object individually using an else-if, you may use a switch statement.

    1. let code = upcCode
    2. switch code {
    3. case .upc(let numberSystem, let manufacturer, let product, let check):
    4. print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
    5. case .qrCode(let productCode):
    6. print("QR code: \(productCode).")

    The code below is identical as above. It gives off zenness.

    Source Code

    7001_enum_basics.playground

    You’ve reviewed the three types of enums in the Swift Programming Language. If you are not comfortable with any, make sure you review and watch this video multiple times to get used to the syntax. Upcoming lessons will get more complex.

    In the following lesson, you will learn how to use Swift enums to type less but produce more using practical examples in iOS development.