2

In Swift, I have a enum and switch-statement like below:

enum Job {
    case all
    case sweep
    case clean
    case wash
}

let job: Job = .all

switch job {
case .all:
    print("should do all the jobs below")
case .sweep:
    print("sweep")
case .clean:
    print("clean")
case .wash:
    print("wash")
}

My question is that how can I modify the switch-statement so that it loops all the cases if the given job is .all. So that the .all case's printed result should be:

sweep
clean
wash

I come up an idea with:

switch job {
case .all: fallthrough
case .sweep:
    print("sweep")
    if job == .all { fallthrough }
case .clean:
    print("clean")
    if job == .all { fallthrough }
case .wash:
    print("wash")
}

and wondering if there is any more 'beautiful' solution. Thanks.

inexcii
  • 1,591
  • 2
  • 15
  • 28
  • 2
    See [How to enumerate an enum with String type?](https://stackoverflow.com/questions/24007461/how-to-enumerate-an-enum-with-string-type) – Martin R Jun 14 '19 at 08:28
  • @MartinR Hi, thank you for the comment. I read the link and using `CaseIterable` is a really beautiful solution. – inexcii Jun 14 '19 at 09:21
  • If the jobs are not mutually exclusive then using an `OptionSet` might be a better solution. – Martin R Jun 14 '19 at 09:36

1 Answers1

3

You could use CaseIterable for your enum and in case of .all just iterate over all cases (except .all) like so:


enum Job: CaseIterable {
    case all, sweep, clean, wash
}

func sweep() {
    print("sweep")
}

func clean() {
    print("clean")
}

func wash() {
    print("wash")
}

let job: Job = .all

func doJob(job: Job) {
    switch job {
        case .all:
            Job.allCases.forEach({
                switch $0 {
                    case .all:
                        break
                    default:
                        doJob(job: $0)
                }
            })
        case .sweep:
            sweep()
        case .clean:
            clean()
        case .wash:
            wash()
    }
}

doJob(job: job)
Eternal Black
  • 259
  • 2
  • 15