You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
8 Hrs
3 Min
22 Seg

Diccionarios

11/25
Resources

How to work with complex data using maps in Swift?

In the world of software development, it is essential to learn how to handle more complex data types in order to represent entities effectively. For example, in an online store, a product must include information such as name, price, stock, description, reviews, among others. For this purpose, Swift offers a powerful data structure known as dictionaries or maps, which allows us to model these entities in an organized way, assigning a "key" to each corresponding value.

How to declare a map in Swift?

To start working with maps, the first thing you need to learn is how to declare them. For example, if you want to create a map in Swift, the declaration would be as follows:

var map: [String: Any] = [ "key1": "value1", "key2": "value2", "key3": 12 ]
  • Keys and values: a map is composed of pairs, where each key is associated with a value. The keys are usually Strings, but the values can be of different types. If the values are varied, Any is used to define as the value type.
  • Explicit data types: Unlike arrays where data types are homogeneous, in maps you can find data of different types, so you must specify the type when defining them as Any.

How to model a product with a dictionary in Swift?

Let's imagine you want to model a product. Here's how you can do it using a map:

var product: [String: Any] = [ "id": 101, "name": "Lenovo PC", "price": 1000, "stock": 10, "promo": true ]

How to access and modify the values in a dictionary?

To access a value in the dictionary, you use its key. Also, you can use as to make sure that the type is the right one:

if let ProductName = product["name"] as? String { print("ProductName: \(productName)") }

Modifying the values is equally simple:

product["stock"] = 1 product["price"] = 2000

How to add and remove keys from a map?

Add data:

product["rating"] = 5

Removing data is straightforward:

  • Using removeValue(forKey:) function:

    product.removeValue(forKey: "promotion")

  • Assigning nil directly to a key:

    product["stock"] = nil

  • Removing all values:

    product.removeAll()

Practice Challenge

Next, you are given a small challenge to reinforce your learning:

Write a function that calculates the number of inhabitants for a given country and returns the following statement: "In [country name] there are [number of inhabitants] inhabitants." In case no information is available, return "I don't have enough data for an enlightening answer."

Here's an example initial setup:

let inhabitantsCountry: [String: Int] = [ "Argentina": 45195777, "Mexico": 126190788, "Brazil": 211000000 ] func getInhabitantsCountry(country: String) -> String { // Function code }

Contributions 7

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Los diccionarios en Swift son estructuras de datos que almacenan pares de clave-valor, permitiendo acceder a los valores mediante sus claves. Son 煤tiles para representar datos complejos, como un producto en una tienda, donde cada producto podr铆a tener propiedades como nombre, precio y stock. Usos comunes incluyen: 1. Almacenar configuraciones de aplicaciones. 2. Representar datos de usuarios. 3. Manejar colecciones de objetos donde cada objeto tiene identificadores 煤nicos. Son flexibles y permiten un acceso r谩pido a los datos, facilitando la programaci贸n orientada a objetos en Swift.
```js let populationByCountry: [String: Int] = [ "Colombia": 48000000, "France": 67000000, "Germany": 83000000, "Spain": 46000000, "Italy": 60000000, "China": 1400000000 ] func getPopulationByCountry(country: String) -> String { return populationByCountry.keys.contains(country) ? "'\(country)' -> \(populationByCountry[country]!)" : "I don't have enough data for a definitive answer." } print(getPopulationByCountry(country: "Colombia")) print(getPopulationByCountry(country: "Mexico")) print(getPopulationByCountry(country: "China")) ```
```js let habitantesPorPais: [String: Int] = [ "Colombia": 48000000, "Argentina": 45195777, "M茅xico": 126190788, "Brasil": 211000000 ] func getHabitantesPorPais(pais: String) -> String { let paisEnviado = habitantesPorPais.keys.contains(pais) if(paisEnviado == true ){ return "En \(pais) hay \(habitantesPorPais[pais]!) habitantes." }else{ return "No tengo datos suficientes para una respuesta esclarecedora." } } print(getHabitantesPorPais(pais: "Colombia")) ```
**let** populationByCountry: \[String: Int] = \[ "Colombia": 48\_000\_000, "France": 67\_000\_000, "Germany": 83\_000\_000, "Spain": 46\_000\_000, "Italy": 60\_000\_000, "China": 1\_400\_000\_000 ] **func** getPopulationByCountry(country: String) -> String { **return** populationByCountry.keys.contains(country) ? "'\\(country)' -> \\(populationByCountry\[country]!)" : "I don't have enough data for a definitive answer." } print(getPopulationByCountry(country: "Colombia")) print(getPopulationByCountry(country: "United States")) print(getPopulationByCountry(country: "China"))
![](https://static.platzi.com/media/user_upload/image-780f2943-79d7-443c-841b-1f17804042a7.jpg)me parecio mas sencillo sin la funcion que recomiendas
```js func getHabitantesPorPais(pais: String) -> String { return habitantesPorPais.keys.contains(pais) ? "En \(pais) hay \(habitantesPorPais[pais]!) habitantes" : "No tengo datos suficientes" } print(getHabitantesPorPais(pais: "Colombia")) print(getHabitantesPorPais(pais: "Mexico")) print(getHabitantesPorPais(pais: "francia")) ```
Aqu铆 mi soluci贸n `func`` getHabitantesPorPais(pais: String) -> String {` `return`` habitantesPorPais.keys.contains(pais)` `? "En \(pais) hay \(habitantesPorPais[pais] ?? 0) habitantes"` `: "No tengo datos suficientes para una respuesta exclarecedora."` `}`