values switch enum computed ios enums swift

ios - enum - switch self swift



Looping a través de valores enum en Swift (1)

Esta pregunta ya tiene una respuesta aquí:

¿Es posible recorrer los valores enum en Swift? ¿O cuál es la alternativa?

Estoy trabajando a través de la guía de lenguaje Swift de Apple, y encontré este ejemplo en enumeraciones.

// EXPERIMENT // // Add a method to Card that creates a full deck of cards, // with one card of each combination of rank and suit. struct Card { var rank: Rank var suit: Suit func simpleDescription() -> String { return "The /(rank.simpleDescription()) of /(suit.simpleDescription())" } } let threeOfSpades = Card(rank: .Three, suit: .Spades) let threeOfSpadesDescription = threeOfSpades.simpleDescription() enum Suit { case Spades, Hearts, Diamonds, Clubs func simpleDescription() -> String { switch self { case .Spades: return "spades" case .Hearts: return "hearts" case .Diamonds: return "diamonds" case .Clubs: return "clubs" } } } enum Rank: Int { case Ace = 1 case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King func simpleDescription() -> String { switch self { case .Ace: return "ace" case .Jack: return "jack" case .Queen: return "queen" case .King: return "king" default: return String(self.toRaw()) } } }

Extracto de: Apple Inc. "The Swift Programming Language". IBooks. https://itun.es/us/jEUH0.l

He intentado lo siguiente, pero los documentos dicen que las enumeraciones en Swift no tienen valores enteros subyacentes como en C, así que probablemente esté ladrando el árbol equivocado.

¿Hay una mejor manera de resolver este problema?

func deck() -> Card[]{ var deck: Card[] for s in Suit { for r in Rank { deck += Card(rank: r, suit: s) } } return deck } func deck2() -> Card[]{ var deck: Card[] for var s: Suit = .Spades; s <= .Clubs; s++ { for var r: Rank = .Ace; r <= .King; r++ { deck += Card(rank: r, suit: s) } } return deck }


¿Hay otra manera? Por supuesto. Es mejor , eso es para que usted decida:

func generateDeck() -> Card[] { let ranksPerSuit = 13 var deck = Card[]() for index in 0..52 { let suit = Suit.fromRaw(index / ranksPerSuit) let rank = Rank.fromRaw(index % ranksPerSuit + 1) let card = Card(rank: rank!, suit: suit!) deck.append(card) } return deck } let deck = generateDeck() for card : Card in deck { println("/(card.description)") }

Para usar esto, necesitarás asegurarte de que las enum de Rank y Suit usan Int para sus definiciones de tipo (ej: enum Rank : Int ).

Rank.Ace debe ser igual a 1 y el primer caso de Suit debe ser igual a 0 .

Si desea hacer un bucle similar a su código existente, aún debe hacer sus enumeraciones tipos Int para que pueda usar Rank.King.toRaw() y similares.

La documentación de Apple establece que las enumeraciones no están restringidas a ser ''simplemente valores enteros'', pero ciertamente pueden serlo si así lo desean.