Isuru Isuru - 1 year ago 163
Swift Question

Get all enum values as an array

I have the following enum.

enum EstimateItemStatus: Printable {
case Pending
case OnHold
case Done

var description: String {
switch self {
case .Pending: return "Pending"
case .OnHold: return "On Hold"
case .Done: return "Done"
}
}

init?(id : Int) {
switch id {
case 1:
self = .Pending
case 2:
self = .OnHold
case 3:
self = .Done
default:
return nil
}
}
}


I need to get all the raw values as an array of strings (like so
["Pending", "On Hold", "Done"]
).

I added this method to the enum.

func toArray() -> [String] {
var n = 1
return Array(
GeneratorOf<EstimateItemStatus> {
return EstimateItemStatus(id: n++)!.description
}
)
}


But I'm getting the following error.

Cannot find an initializer for type 'GeneratorOf' that accepts an argument list of type '(() -> _)'

I can't figure out how to resolve this. Any help? Or please tell me if there is an easier/better/more elegant way to do this.

Thank you.

Answer Source

I found somewhere this code:

protocol EnumCollection : Hashable {}


extension EnumCollection {

    static func cases() -> AnySequence<Self> {
        typealias S = Self
        return AnySequence { () -> AnyGenerator<S> in
            var raw = 0
            return AnyGenerator {
                let current : Self = withUnsafePointer(&raw) { UnsafePointer($0).memory }
                guard current.hashValue == raw else { return nil }
                raw += 1
                return current
            }
        }
    }
}

Use:

enum YourEnum: EnumCollection { //code }

YourEnum.cases()

return list of cases from YourEnum

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download