Iterating through an Enum in Swift 3.0

前端 未结 6 435
野性不改
野性不改 2021-01-06 02:35

I have a simple enum that I would like to iterate over. For this purpose, I\'ve adopted Sequence and IteratorProtocol as shown in the code below. BTW, this can be copy/paste

6条回答
  •  醉梦人生
    2021-01-06 03:21

    Update: As of Swift 4.2, you can simply add protocol conformance to CaseIterable, see How to enumerate an enum with String type?.


    You can iterate over a value of a type which conforms to the Sequence protocol. Therefore

    for section in Sections.Section0 {
      print(section)
    }
    

    would compile and give the expected result. But of course that is not really what you want because the choice of the value is arbitrary and the value itself not needed in the sequence.

    As far as I know, there is no way to iterate over a type itself, so that

    for section in Sections {
      print(section)
    }
    

    compiles. That would require that the "metatype" Sections.Type conforms to Sequence. Perhaps someone proves me wrong.

    What you can do is to define a type method which returns a sequence:

    extension Sections {
        static func all() -> AnySequence {
            return AnySequence {
                return SectionsGenerator()
            }
        }
    
        struct SectionsGenerator: IteratorProtocol {
            var currentSection = 0
    
            mutating func next() -> Sections? {
                guard let item = Sections(rawValue:currentSection) else {
                    return nil
                }
                currentSection += 1
                return item
            }
        }
    
    }
    
    for section in Sections.all() {
        print(section)
    }
    

提交回复
热议问题