Come ottenere tutti i valori enum come array


99

Ho la seguente enumerazione.

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
        }
    }
}

Ho bisogno di ottenere tutti i valori grezzi come un array di stringhe (in questo modo ["Pending", "On Hold", "Done"]).

Ho aggiunto questo metodo al file enum.

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

Ma ricevo il seguente errore.

Impossibile trovare un inizializzatore per il tipo "GeneratorOf" che accetti un elenco di argomenti di tipo "(() -> _)"

Esiste un modo più semplice, migliore o più elegante per farlo?


2
puoi creare un array come let array: [CertainItemStatus] = [.Pending, .Onhold, .Done]
Kristijan Delivuk

1
@KristijanDelivuk Voglio aggiungere questa funzionalità all'enumerazione stessa. Quindi non devo andare e aggiungerlo ovunque in altri punti delle basi di codice se aggiungo un altro valore all'enumerazione.
Isuru


Ho una risposta si può fare riferimento a qui stackoverflow.com/a/48960126/5372480
MSimic

Risposte:


146

Per Swift 4.2 (Xcode 10) e versioni successive

C'è un CaseIterableprotocollo:

enum EstimateItemStatus: String, CaseIterable {
    case pending = "Pending"
    case onHold = "OnHold"
    case done = "Done"

    init?(id : Int) {
        switch id {
        case 1: self = .pending
        case 2: self = .onHold
        case 3: self = .done
        default: return nil
        }
    }
}

for value in EstimateItemStatus.allCases {
    print(value)
}

Per Swift <4.2

No, non puoi interrogare un enumper quali valori contiene. Vedi questo articolo . Devi definire un array che elenchi tutti i valori che hai. Controlla anche la soluzione di Frank Valbuena in " Come ottenere tutti i valori enum come array ".

enum EstimateItemStatus: String {
    case Pending = "Pending"
    case OnHold = "OnHold"
    case Done = "Done"

    static let allValues = [Pending, OnHold, Done]

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

for value in EstimateItemStatus.allValues {
    print(value)
}

Vedi questa risposta: stackoverflow.com/a/28341290/8047 incluso il codice Swift 3.
Dan Rosenstark

3
Upvoting per la parte allValues, ma non sono sicuro di cosa provare se un'enumerazione è di tipo String ma inizializzata con Int.
Tyress

Il primo collegamento è interrotto ma sembra essere in exceptionshub.com/… ora.
Tin Man,

39

Swift 4.2 introduce un nuovo protocollo denominatoCaseIterable

enum Fruit : CaseIterable {
    case apple , apricot , orange, lemon
}

a cui, quando ci si conforma, è possibile ottenere un array dai enumcasi come questo

for fruit in Fruit.allCases {
    print("I like eating \(fruit).")
}

26

Aggiungi il protocollo CaseIterable a enum:

enum EstimateItemStatus: String, CaseIterable {
    case pending = "Pending"
    case onHold = "OnHold"
    case done = "Done"
}

Utilizzo:

let values: [String] = EstimateItemStatus.allCases.map { $0.rawValue }
//["Pending", "OnHold", "Done"]

17

C'è un altro modo che almeno è sicuro in fase di compilazione:

enum MyEnum {
    case case1
    case case2
    case case3
}

extension MyEnum {
    static var allValues: [MyEnum] {
        var allValues: [MyEnum] = []
        switch (MyEnum.case1) {
        case .case1: allValues.append(.case1); fallthrough
        case .case2: allValues.append(.case2); fallthrough
        case .case3: allValues.append(.case3)
        }
        return allValues
    }
}

Nota che questo funziona per qualsiasi tipo di enum (RawRepresentable o meno) e anche se aggiungi un nuovo caso, otterrai un errore del compilatore che è buono poiché ti costringerà ad averlo aggiornato.


1
Non ortodosso, ma funziona e ti avverte se modifichi i casi enum. Soluzione intelligente!
Chuck Krutsinger

12

Ho trovato da qualche parte questo codice:

protocol EnumCollection : Hashable {}


extension EnumCollection {

    static func cases() -> AnySequence<Self> {
        typealias S = Self
        return AnySequence { () -> AnyIterator<S> in
            var raw = 0
            return AnyIterator {
                let current : Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: S.self, capacity: 1) { $0.pointee }
                }
                guard current.hashValue == raw else { return nil }
                raw += 1
                return current
            }
        }
    }
}

Uso:

enum YourEnum: EnumCollection { //code }

YourEnum.cases()

restituire l'elenco dei casi da YourEnum


Sembra un'ottima soluzione ma presenta alcuni errori di compilazione su Swift 4.
Isuru

1
Il "da qualche parte" potrebbe essere: theswiftdev.com/2017/10/12/swift-enum-all-values (tra gli altri?). Il blogger attribuisce CoreKit .
AmitaiB

5
Ciò interrompe XCode 10 (indipendentemente dalla versione Swift) poiché hashValue di un'enumerazione non più incrementale ma casuale, interrompendo il meccanismo. Il nuovo modo per farlo è aggiornare a Swift 4.2 e utilizzare CaseIterable
Yasper

8

Per ottenere una lista per scopi funzionali, usa l'espressione EnumName.allCasesche restituisce un array es

EnumName.allCases.map{$0.rawValue} 

ti darà un elenco di stringhe dato questo EnumName: String, CaseIterable

Nota: usa allCasesinvece di AllCases().


8
enum EstimateItemStatus: String, CaseIterable {
  case pending = "Pending"
  case onHold = "OnHold"
  case done = "Done"

  static var statusList: [String] {
    return EstimateItemStatus.allCases.map { $0.rawValue }
  }
}

["In attesa", "In attesa", "Fine"]


2

Aggiornamento per Swift 5

La soluzione più semplice che ho trovato è da usare .allCasessu un'enumerazione che si estendeCaseIterable

enum EstimateItemStatus: CaseIterable {
    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
        }
    }
}

.allCasessu qualsiasi CaseIterableenum restituirà un Collectiondi quell'elemento.

var myEnumArray = EstimateItemStatus.allCases

maggiori informazioni su CaseIterable


Non è necessario implementare description (). Basta equiparare ogni caso alla stringa, ad esempio, case OnHold = "On Hold"e questo diventa il valore grezzo per ciascuno.
pnizzle

@pnizzle Lo so, è lì perché era nella domanda originale.
Christopher Larsen

1

Per Swift 2

// Found http://stackoverflow.com/questions/24007461/how-to-enumerate-an-enum-with-string-type
func iterateEnum<T where T: Hashable, T: RawRepresentable>(_: T.Type) -> AnyGenerator<T> {
    var i = 0
    return AnyGenerator {
        let next = withUnsafePointer(&i) {
            UnsafePointer<T>($0).memory
        }
        if next.hashValue == i {
            i += 1
            return next
        } else {
            return nil
        }
    }
}

func arrayEnum<T where T: Hashable, T: RawRepresentable>(type: T.Type) -> [T]{
    return Array(iterateEnum(type))
}

Per usarlo:

arrayEnum(MyEnumClass.self)

Perché dovrebbero hashValueesserci gli elementi 0..n?
NRitH

1

Dopo l'ispirazione dalla sequenza e ore di tentativi n errori. Finalmente ho ottenuto questo comodo e bellissimo Swift 4 su Xcode 9.1:

protocol EnumSequenceElement: Strideable {
    var rawValue: Int { get }
    init?(rawValue: Int)
}

extension EnumSequenceElement {
    func distance(to other: Self) -> Int {
        return other.rawValue - rawValue
    }

    func advanced(by n: Int) -> Self {
        return Self(rawValue: n + rawValue) ?? self
    }
}

struct EnumSequence<T: EnumSequenceElement>: Sequence, IteratorProtocol {
    typealias Element = T

    var current: Element? = T.init(rawValue: 0)

    mutating func next() -> Element? {
        defer {
            if let current = current {
                self.current = T.init(rawValue: current.rawValue + 1)
            }
        }
        return current
    }
}

Utilizzo:

enum EstimateItemStatus: Int, EnumSequenceElement, CustomStringConvertible {
    case Pending
    case OnHold
    case Done

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

for status in EnumSequence<EstimateItemStatus>() {
    print(status)
}
// Or by countable range iteration
for status: EstimateItemStatus in .Pending ... .Done {
    print(status)
}

Produzione:

Pending
On Hold
Done

1

Puoi usare

enum Status: Int{
    case a
    case b
    case c

}

extension RawRepresentable where Self.RawValue == Int {

    static var values: [Self] {
        var values: [Self] = []
        var index = 1
        while let element = self.init(rawValue: index) {
            values.append(element)
            index += 1
        }
        return values
    }
}


Status.values.forEach { (st) in
    print(st)
}

Bello! Dopo l'aggiornamento da Swift 3.2 a 4.1 questa era una soluzione che ho usato. Inizialmente avevamo dichiarazioni AnyItertor <Self>. La tua soluzione era molto più pulita e più facile da leggere. Grazie!
Nick N

2
Un difetto di codice qui però. Manca il primo elemento della custodia. Cambia var index = 1 in var index = 0
Nick N

0

Se la tua enumerazione è incrementale e associata a numeri, puoi utilizzare l'intervallo di numeri che mappi per enumerare i valori, in questo modo:

// Swift 3
enum EstimateItemStatus: Int {
    case pending = 1,
    onHold
    done
}

let estimateItemStatusValues: [EstimateItemStatus?] = (EstimateItemStatus.pending.rawValue...EstimateItemStatus.done.rawValue).map { EstimateItemStatus(rawValue: $0) }

Non funziona con le enumerazioni associate a stringhe o qualsiasi altra cosa diversa dai numeri, ma funziona benissimo se è così!


0

Estensione su un'enumerazione per creare allValues.

extension RawRepresentable where Self: CaseIterable {
      static var allValues: [Self.RawValue] {
        return self.allCases.map { $0.rawValue}
      }
    }

Sebbene questo codice possa fornire una soluzione al problema di OP, si consiglia vivamente di fornire un contesto aggiuntivo riguardo al motivo e / o al modo in cui questo codice risponde alla domanda. Le risposte basate solo sul codice in genere diventano inutili nel lungo periodo perché i futuri spettatori che hanno problemi simili non possono comprendere il ragionamento alla base della soluzione.
E. Zeytinci
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.