|
1 | 1 | ---
|
2 |
| -title: Nested Types |
| 2 | +title: Tipos Anidados |
3 | 3 | ---
|
4 | 4 |
|
| 5 | +import Callout from '@components/Callout' |
5 | 6 | import Hero from '@components/Hero'
|
6 | 7 |
|
7 | 8 | <Hero>
|
8 |
| - # Nested Types |
| 9 | + # Tipos Anidados |
9 | 10 |
|
10 |
| - Define types inside the scope of another type. |
| 11 | + Define tipos dentro del ámbito de otro tipo. |
11 | 12 | </Hero>
|
12 | 13 |
|
13 |
| -Enumerations are often created to support a specific class or structure's functionality. Similarly, it can be convenient to define utility classes and structures purely for use within the context of a more complex type. To accomplish this, Swift enables you to define _nested types_, whereby you nest supporting enumerations, classes, and structures within the definition of the type they support. |
| 14 | +Las enumeraciones suelen crearse para apoyar la funcionalidad de una clase o estructura específica. De forma similar, puede ser útil definir clases y estructuras utilitarias con el único fin de usarlas dentro del contexto de un tipo más complejo. Para lograr esto, Swift te permite definir _tipos anidados_, mediante los cuales puedes anidar enumeraciones, clases y estructuras de soporte dentro de la definición del tipo que soportan. |
14 | 15 |
|
15 |
| -To nest a type within another type, write its definition within the outer braces of the type it supports. Types can be nested to as many levels as are required. |
| 16 | +Para anidar un tipo dentro de otro tipo, escribe su definición dentro de las llaves exteriores del tipo que soporta. Los tipos pueden anidarse en tantos niveles como sea necesario. |
16 | 17 |
|
17 |
| -## Nested Types in Action |
| 18 | +## Tipos anidados en acción |
18 | 19 |
|
19 |
| -The example below defines a structure called `BlackjackCard`, which models a playing card as used in the game of Blackjack. The `BlackjackCard` structure contains two nested enumeration types called `Suit` and `Rank`. |
| 20 | +El siguiente ejemplo define una estructura llamada `CartaBlackjack`, la cual modela una carta tal y como se utiliza en el juego del Blackjack. La estructura `CartaBlackjack` contiene dos tipos de enumeración anidados llamados `Palo` y `Rango`. |
20 | 21 |
|
21 |
| -In Blackjack, the Ace cards have a value of either one or eleven. This feature is represented by a structure called Values, which is nested within the `Rank` enumeration: |
| 22 | +En Blackjack, los ases tienen un valor de uno u once. Esta característica está representada por una estructura llamada `Valores`, la cual se encuentra anidada dentro de la enumeración `Rango`: |
22 | 23 |
|
23 | 24 | ```swift showLineNumbers
|
24 |
| -struct BlackjackCard { |
| 25 | +struct CartaBlackjack { |
25 | 26 |
|
26 |
| - // nested Suit enumeration |
27 |
| - enum Suit: Character { |
28 |
| - case spades = "♠", hearts = "♡", diamonds = "♢", clubs = "♣" |
| 27 | + // Enumeración anidada Palo |
| 28 | + enum Palo: Character { |
| 29 | + case picas = "♠", corazones = "♡", diamantes = "♢", treboles = "♣" |
29 | 30 | }
|
30 | 31 |
|
31 |
| - // nested Rank enumeration |
32 |
| - enum Rank: Int { |
33 |
| - case two = 2, three, four, five, six, seven, eight, nine, ten |
34 |
| - case jack, queen, king, ace |
| 32 | + // Enumeración anidada Rango |
| 33 | + enum Rango: Int { |
| 34 | + case dos = 2, tres, cuatro, cinco, seis, siete, ocho, nueve, diez |
| 35 | + case jota, reina, rey, _as |
35 | 36 |
|
36 |
| - // nested Values structure |
37 |
| - struct Values { |
38 |
| - let first: Int, second: Int? |
| 37 | + // Estructura anidada Valores |
| 38 | + struct Valores { |
| 39 | + let primero: Int, segundo: Int? |
39 | 40 | }
|
40 | 41 |
|
41 |
| - var values: Values { |
| 42 | + var valores: Valores { |
42 | 43 | switch self {
|
43 |
| - case .ace: |
44 |
| - return Values(first: 1, second: 11) |
45 |
| - case .jack, .queen, .king: |
46 |
| - return Values(first: 10, second: nil) |
| 44 | + case ._as: |
| 45 | + return Valores(primero: 1, segundo: 11) |
| 46 | + case .jota, .reina, .rey: |
| 47 | + return Valores(primero: 10, segundo: nil) |
47 | 48 | default:
|
48 |
| - return Values(first: self.rawValue, second: nil) |
| 49 | + return Valores(primero: self.rawValue, segundo: nil) |
49 | 50 | }
|
50 | 51 | }
|
51 | 52 | }
|
52 | 53 |
|
53 |
| - // BlackjackCard properties and methods |
54 |
| - let rank: Rank, suit: Suit |
| 54 | + // Propiedades y métodos de CartaBlackjack |
| 55 | + let rango: Rango, palo: Palo |
55 | 56 |
|
56 |
| - var description: String { |
57 |
| - var output = "suit is \(suit.rawValue)," |
58 |
| - output += " value is \(rank.values.first)" |
| 57 | + var descripcion: String { |
| 58 | + var resultado = "el palo es \(palo.rawValue)," |
| 59 | + resultado += " el valor es \(rango.valores.primero)" |
59 | 60 |
|
60 |
| - if let second = rank.values.second { |
61 |
| - output += " or \(second)" |
| 61 | + if let segundo = rango.valores.segundo { |
| 62 | + resultado += " u \(segundo)" |
62 | 63 | }
|
63 | 64 |
|
64 |
| - return output |
| 65 | + return resultado |
65 | 66 | }
|
66 | 67 | }
|
67 | 68 | ```
|
68 | 69 |
|
69 |
| -The `Suit` enumeration describes the four common playing card suits, together with |
70 |
| -a raw `Character` value to represent their symbol. |
| 70 | +La enumeración `Palo` describe los cuatro palos habituales de la baraja, junto con un valor `Character` en bruto para representar su símbolo. |
71 | 71 |
|
72 |
| -The `Rank` enumeration describes the thirteen possible playing card ranks, together with a raw `Int` value to represent their face value. (This raw `Int` value isn't used for the Jack, Queen, King, and Ace cards.) |
| 72 | +La enumeración `Rango` describe los trece posibles valores de rango de la baraja, junto con un valor `Int` en bruto para representar su valor nominal (este valor `Int` en bruto no se usa para los naipes Jota, Reina, Rey y As). |
73 | 73 |
|
74 |
| -As mentioned above, the Rank enumeration defines a further nested structure of its own, called `Values`. This structure encapsulates the fact that most cards have one value, but the Ace card has two values. The `Values` structure defines two properties to represent this: |
| 74 | +Como se mencionó anteriormente, la enumeración `Rango` define una estructura anidada propia, llamada `Valores`. Esta estructura encapsula el hecho de que la mayoría de las cartas tienen un valor, mientras que la carta As tiene dos valores. La estructura `Valores` define dos propiedades para representar esto: |
75 | 75 |
|
76 |
| -- first, of type `Int` |
77 |
| -- second, of type `Int?`, or “optional `Int`” |
| 76 | +- `primero`, de tipo `Int` |
| 77 | +- `segundo`, de tipo `Int?`, o "`Int` opcional" |
78 | 78 |
|
79 |
| -Rank also defines a computed property, `values`, which returns an instance of the `Values` structure. This computed property considers the rank of the card and initializes a new `Values` instance with appropriate values based on its rank. It uses special values for `jack`, `queen`, `king`, and `ace`. For the numeric cards, it uses the rank's raw `Int` value. |
| 79 | +`Rango` también define una propiedad calculada, `valores`, la cual devuelve una instancia de la estructura `Valores`. Esta propiedad calculada analiza el rango de la carta e inicializa una nueva instancia de `Valores` con los valores adecuados acorde a su rango. Esta utiliza valores especiales para `jota`, `reina`, `rey` y `_as`. Para las cartas numéricas, utiliza el valor `Int` en bruto del rango. |
80 | 80 |
|
81 |
| -The `BlackjackCard` structure itself has two properties—`rank` and `suit`. It also defines a computed property called `description`, which uses the values stored in `rank` and `suit` to build a description of the name and value of the card. The `description` property uses optional binding to check whether there's a second value to display, and if so, inserts additional description detail for that second value. |
| 81 | +La estructura `CartaBlackjack` tiene dos propiedades: `rango` y `palo`. También define una propiedad calculada llamada `descripcion`, la cual usa los valores almacenados en `rango` y `palo` para componer una descripción del nombre y valor de la carta. La propiedad `descripcion` utiliza la vinculación opcional para comprobar si hay un segundo valor que mostrar y, de ser así, añade detalles adicionales para la descripción de dicho segundo valor. |
82 | 82 |
|
83 |
| -Because `BlackjackCard` is a structure with no custom initializers, it has an implicit memberwise initializer, as described in [Memberwise Initializers for Structure Types](./inicializacion). You can use this initializer to initialize a new constant called `theAceOfSpades`: |
| 83 | +Dado que `CartaBlackjack` es una estructura sin inicializadores a medida, tiene un inicializador de miembros implícito, como se describe en[Inicializadores de miembros para las estrucuturas](./inicializacion#inicializadores-de-miembros-para-las-estructuras). Puedes usar este inicializador para inicializar una nueva constante llamada `elAsDePicas`: |
84 | 84 |
|
85 |
| -```swift showLineNumbers |
86 |
| -let theAceOfSpades = BlackjackCard(rank: .ace, suit: .spades) |
| 85 | +```swift showLineNumbers {1} |
| 86 | +let elAsDePicas = CartaBlackjack(rango: ._as, palo: .picas) |
87 | 87 |
|
88 |
| -print("theAceOfSpades: \(theAceOfSpades.description)") |
89 |
| -// Prints "theAceOfSpades: suit is ♠, value is 1 or 11" |
| 88 | +print("elAsDePicas: \(elAsDePicas.descripcion)") |
| 89 | +// Imprime "elAsDePicas: el palo es ♠, el valor es 1 u 11" |
90 | 90 | ```
|
91 | 91 |
|
92 |
| -Even though `Rank` and `Suit` are nested within `BlackjackCard`, their type can be inferred from context, and so the initialization of this instance is able to refer to the enumeration cases by their case names (`.ace` and `.spades`) alone. In the example above, the `description` property correctly reports that the Ace of Spades has a value of `1` or `11`. |
| 92 | +Aun cuando `Rango` y `Palo` están anidadas dentro de `CartaBlackjack`, su tipo se puede deducir del contexto, por lo que la inicialización de esta instancia se puede permitir referenciar a los casos de la enumeración simplemente por sus nombres de caso (`.as` y `.picas`). En el ejemplo anterior, la propiedad `descripcion` informa, de manera correcta, que el As de Picas tiene un valor de `1` u `11`. |
93 | 93 |
|
94 |
| -## Referring to Nested Types |
| 94 | +## Referencias a tipos anidados |
95 | 95 |
|
96 |
| -To use a nested type outside of its definition context, prefix its name with the name of the type it's nested within: |
| 96 | +Para usar un tipo anidado fuera de su contexto de definición, añade como prefijo a su nombre el nombre del tipo en el que está anidado: |
97 | 97 |
|
98 | 98 | ```swift showLineNumbers
|
99 |
| -let heartsSymbol = BlackjackCard.Suit.hearts.rawValue |
100 |
| -// heartsSymbol is "♡" |
| 99 | +let simboloDeCorazones = CartaBlackjack.Palo.corazones.rawValue |
| 100 | +// simboloDeCorazones es "♡" |
101 | 101 | ```
|
102 | 102 |
|
103 |
| -For the example above, this enables the names of `Suit`, `Rank`, and `Values` to be kept deliberately short, because their names are naturally qualified by the context in which they're defined. |
| 103 | +En el ejemplo anterior, esto permite mantener los nombres de `Palo`, `Rango` y `Valores` deliberadamente cortos, ya que sus nombres están naturalmente cualificados por el contexto en el que se definen. |
| 104 | + |
| 105 | +<Callout type="beta"> |
| 106 | + Esta documentación contiene información preliminar sobre una API o tecnología |
| 107 | + en desarrollo. Esta información está sujeta a cambios, y todo software |
| 108 | + implementado en conformidad con esta documentación debe ser testeado con el |
| 109 | + software final del sistema operativo. |
| 110 | + <br /> |
| 111 | + Conoce más acerca del uso de [software beta de Apple](https://developer.apple.com/es/support/beta-software/). |
| 112 | +</Callout> |
0 commit comments