Home > Software design >  Is it possible group & represent multiple cases as another case within an enum in Swift?
Is it possible group & represent multiple cases as another case within an enum in Swift?

Time:09-21

This is what I mean.

enum Device {
    case iPhone_13Pro, iPhone_12Pro
    
    case iPadPro_129
    case iPadPro_11
}

// Hypothetical Scenario
enum Device_Group {
    case iPhones
    case iPads
}

Is there any way to do as above to represent a certain group of cases like this (it can be another enum OR a different case within the same enum - so that I could do as below?

// DO THIS
switch device {
   case iPhones:
        print("These are iPhones")

   case iPads:
        print("These are iPads")
}

// INSTEAD OF THIS
switch device {
   case .iPhone_13Pro, .iPhone_12Pro:
        print("These are iPhones")

   case .iPadPro_129, .iPadPro_11:
        print("These are iPads")
}

I dont know if this might be a weird question, but I find that grouping multiple cases has a certain benefit while using a switch statement. Would appreciate any advise on this. Thanks in advance.

CodePudding user response:

You can used nested Enum and a case with parameter

enum Devices {
    case phone(iPhone)
    case tablet(iPad)

    enum iPhone {
        case phone7
        case phoneX
    }

    enum iPad {
        case mini
        case pro
    }
}

let randomDevice = Devices.phone(.phone7)

switch randomDevice {
    case .phone: 
        print("Its a phone")
    default:
        break
}

// prints "Its a phone"

CodePudding user response:

You can define two different enums for iPhones and iPads and then use them as Associated Values for Devices's types.

https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html


enum Ipad {
    case iPadAir
    case iPadPro
}

enum Iphone {
    case iPhone12
    case iPhone13
}

enum Device {
    case iPad(model: Ipad)
    case iPhone(model: Iphone)
}

func findDeviceType(device: Device) {
    switch device {
    case .iPad:
        print("iPad")
    case .iPhone:
        print("iPhone")
    }
}

findDeviceType(device: Device.iPad(model: .iPadAir)) // iPad

CodePudding user response:

You can look at OptionSet as well and it's flexible approach to group and serialize your items because they have unique values. For instance:

struct Device: OptionSet {
    let rawValue: Int

    static let iPhone_13Pro = Self(rawValue: 1 << 0)
    static let iPhone_12Pro = Self(rawValue: 1 << 1)
    
    static let iPadPro_129 = Self(rawValue: 1 << 2)
    static let iPadPro_11 =  Self(rawValue: 1 << 3)

    static let iPhone: Self = [.iPhone_13Pro, .iPhone_12Pro]
    static let iPad: Self = [.iPadPro_129, .iPadPro_11]
    
    static let all: Self = [.iPhone, .iPad]
}

let device = Device.iPhone_13Pro

if Device.iPhone.contains(device) {
    print("It's iPhone")
}
  • Related