DEV Community

Michael
Michael

Posted on • Updated on

Swift Notes: Enums

This is a collection of code-snippets that I've accumulated on my journey of learning iOS Development with Swift; I'm hoping it can serve as a cheat-sheet or resource for others learning.

Enums

Swift is smart and will iterate the rawValues of your enum from 0 or according to whatever initial value(s) you set

enum WinterMonth: Int {
  case December = 1
  case January /// 2
  case February /// 3
}

print(WinterMonth.January.rawValue) /// 2
Enter fullscreen mode Exit fullscreen mode

Iterate over all values of an enum with the CaseIterable Protocol

enum WinterMonth: String, CaseIterable {
  case December
  case January
  case February
}

var monthsArray = WinterMonth.allCases
Enter fullscreen mode Exit fullscreen mode

Comparing enums using Swift's type system

/// Switch Statement 
enum WinterMonth {
  case December
  case January
  case February
}

let currentMonth = WinterMonth.January

switch currentMonth {
  case .December:
    print("Happy Holidays!")
  case .January:
    print("Happy New Year!")
  default:
    print("It is \(currentMonth)")
}
Enter fullscreen mode Exit fullscreen mode

Enum containing different data types

enum Result {
    case success(Value)
    case failure(Error)
}

extension Result {
    /// The error in case the result was a failure
    public var error: Error? {
        guard case .failure(let error) = self else { return nil }
        return error
    }

    /// The value in case the result was a success result.
    public var value: Value? {
        guard case .success(let value) = self else { return nil }
        return value
    }
}
Enter fullscreen mode Exit fullscreen mode

ts




Enter fullscreen mode Exit fullscreen mode

Discussion (0)