Iterating through an Enum in Swift 3.0

≯℡__Kan透↙ 提交于 2019-11-30 20:58:44

Note that Martin’s solution can be refactored as a protocol:

import Foundation

protocol EnumSequence
{
    associatedtype T: RawRepresentable where T.RawValue == Int
    static func all() -> AnySequence<T>
}
extension EnumSequence
{
    static func all() -> AnySequence<T> {
        return AnySequence { return EnumGenerator() }
    }
}

private struct EnumGenerator<T: RawRepresentable>: IteratorProtocol where T.RawValue == Int {
    var index = 0
    mutating func next() -> T? {
        guard let item = T(rawValue: index) else {
            return nil
        }
        index += 1
        return item
    }
}

Then, given an enum

enum Fruits: Int {
    case apple, orange, pear
}

you slap the protocol and a typealias:

enum Fruits: Int, EnumSequence {
    typealias T = Fruits
    case apple, orange, pear
}

Fruits.all().forEach({ print($0) }) // apple orange pear

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<Sections> {
        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)
}

This looks so much simpler:

public protocol EnumSequence {
    init?(rawValue: Int)
}

public extension EnumSequence {

    public static var items: [Self] {
        var caseIndex: Int = 0
        let interator: AnyIterator<Self> = AnyIterator {
            let result = Self(rawValue: caseIndex)
            caseIndex += 1
            return result
        }
        return Array(interator)
    }
}

Simply add to enum: static var allTypes: [Sections] = [.Section0, .Section1, .Section2]

And than you can:

Sections.allTypes.forEach { (section) in
            print("\(section)")
}

Iterated upon the solutions above, see below a protocol that can be implemented by enumerations to add the allValues sequence but also to allow the possibility to convert to and from string value.

Very convenient for String-like enumerations which need to support objective c (only int enumerations are allowed there).

public protocol ObjcEnumeration: LosslessStringConvertible, RawRepresentable where RawValue == Int {
    static var allValues: AnySequence<Self> { get }
}

public extension ObjcEnumeration {
    public static var allValues: AnySequence<Self> {
        return AnySequence {
            return IntegerEnumIterator()
        }
    }

    public init?(_ description: String) {
        guard let enumValue = Self.allValues.first(where: { $0.description == description }) else {
            return nil
        }
        self.init(rawValue: enumValue.rawValue)
    }

    public var description: String {
        return String(describing: self)
    }
}

fileprivate struct IntegerEnumIterator<T: RawRepresentable>: IteratorProtocol where T.RawValue == Int {
    private var index = 0
    mutating func next() -> T? {
        defer {
            index += 1
        }
        return T(rawValue: index)
    }
}

For a concrete example:

@objc
enum Fruit: Int, ObjcEnumeration {
    case apple, orange, pear
}

Now you can do:

for fruit in Fruit.allValues {

    //Prints: "apple", "orange", "pear"
    print("Fruit: \(fruit.description)")

    if let otherFruit = Fruit(fruit.description), fruit == otherFruit {
        print("Fruit could be constructed successfully from its description!")
    }
}

If your enum is an Int based one, you can do an effective but slightly dirty trick like this.

enum MyEnum: Int {
    case One
    case Two
}

extension MyEnum {
    func static allCases() -> [MyEnum] {
        var allCases = [MyEnum]()
        for i in 0..<10000 {
            if let type = MyEnum(rawValue: i) {
                allCases.append(type)
            } else {
                break
            }
        }
        return allCases
    }
}

Then loop over MyEnum.allCases()..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!