Từ điển Swift (Có ví dụ)

Trong hướng dẫn này, bạn sẽ tìm hiểu về từ điển là gì, cách tạo từ điển và một số thao tác thông dụng trong từ điển.

Trong bài viết Mảng Swift trước, chúng ta đã học cách có thể lưu trữ nhiều giá trị trong một biến / hằng số. Trong bài viết này, chúng ta sẽ thảo luận về cách chúng ta có thể lưu trữ dữ liệu / giá trị dưới dạng các cặp giá trị khóa.

Từ điển là gì?

Từ điển chỉ đơn giản là một vùng chứa có thể chứa nhiều dữ liệu dưới dạng cặp khóa-giá trị theo cách không có thứ tự.

Mỗi giá trị được liên kết với một khóa duy nhất và lưu trữ dữ liệu trong danh sách không có thứ tự như của Bộ, tức là bạn không nhận được các phần tử theo thứ tự như bạn đã xác định các mục trong từ điển.

Bạn có thể sử dụng từ điển thay vì mảng khi bạn cần tra cứu giá trị với một số định danh trong bộ sưu tập. Giả sử, bạn có thể muốn tìm kiếm thành phố thủ đô của đất nước. Trong trường hợp đó, bạn sẽ tạo một từ điển với quốc gia chính và thành phố thủ đô giá trị. Bây giờ, bạn lấy thành phố thủ đô từ bộ sưu tập bằng cách tìm kiếm với quốc gia quan trọng.

Nói một cách dễ hiểu, bạn ghép một khóa với một giá trị. Trong ví dụ trên, chúng tôi đã ghép một quốc gia với thành phố thủ đô của nó.

Làm thế nào để khai báo một từ điển trong Swift?

Bạn có thể tạo một từ điển trống bằng cách chỉ định key:valueKiểu dữ liệu bên trong dấu ngoặc vuông ().

Ví dụ 1: Khai báo một từ điển trống

 let emptyDic:(Int:String) = (:) print(emptyDic) 

Khi bạn chạy chương trình, đầu ra sẽ là:

 (:)

HOẶC LÀ

Bạn cũng có thể xác định một từ điển trống như sau:

 let emptyDic:Dictionary = (:) print(emptyDic) 

Trong chương trình trên, chúng ta đã khai báo một từ điển kiểu không đổi voidDic với khóa là kiểu Intvà giá trị của kiểu Stringvà khởi tạo nó bằng 0 giá trị.

HOẶC LÀ

Vì Swift là một ngôn ngữ suy luận kiểu, bạn cũng có thể tạo từ điển trực tiếp mà không cần chỉ định Kiểu dữ liệu nhưng phải khởi tạo với một số giá trị để trình biên dịch có thể suy ra kiểu của nó là:

Ví dụ 2: Khai báo một từ điển với một số giá trị

 let someDic = ("a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9) print(someDic) 

Khi bạn chạy chương trình, đầu ra sẽ là:

 ("b": 2, "a": 1, "i": 9, "c": 3, "e": 5, "f": 6, "g": 7, "d": 4, " h ": 8)

Trong chương trình trên, chúng ta đã khai báo một từ điển mà không xác định kiểu một cách rõ ràng nhưng khởi tạo bằng một số phần tử mặc định.

Phần tử nằm trong cặp khóa: giá trị trong đó khóa thuộc loại Stringvà giá trị thuộc Intloại. Vì từ điển là một danh sách không có thứ tự nên print(someDic)xuất các giá trị theo thứ tự khác với thứ tự đã định nghĩa.

Ví dụ 3: Tạo từ điển từ hai mảng

Chúng ta cũng có thể tạo từ điển bằng cách sử dụng mảng.

 let customKeys = ("Facebook", "Google", "Amazon") let customValues = ("Mark", "Larry", "Jeff") let newDictionary = Dictionary(uniqueKeysWithValues: zip(customKeys,customValues)) print(newDictionary) 

Khi bạn chạy chương trình, đầu ra sẽ là:

 ("Amazon": "Jeff", "Google": "Larry", "Facebook": "Mark")

Trong chương trình trên, zip(customKeys,customValues)tạo một Chuỗi tuple mới với mỗi phần tử đại diện cho giá trị từ customKeys và customValues. Để tìm hiểu thêm về cách hoạt động của zip, hãy truy cập Swit zip.

Bây giờ, chúng ta có thể chuyển chuỗi này tới trình Dictionary(uniqueKeysWithValues:)khởi tạo và tạo một Từ điển mới. Do đó, print(newDictionary)xuất một Từ điển mới với các phần tử từ hai mảng.

How to access dictionary elements in Swift?

As arrays, you can access elements of a dictionary by using subscript syntax . You need to include key of the value you want to access within square brackets immediately after the name of the dictionary.

Example 4: Accessing elements of a dictionary

 let someDic = ("a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9) print(someDic("a")) print(someDic("h")) 

When you run the program, the output will be:

 Optional(1) Optional(8) 

You can also access elements of an dictionary using for-in loops.

Example 5: Accessing elements of an dictionary with for-in loop

 let someDic = ("a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9) for (key,value) in someDic ( print("key:(key) value:(value)") ) 

When you run the program, the output will be:

 key:b value:2 key:a value:1 key:i value:9 key:c value:3 key:e value:5 key:f value:6 key:g value:7 

How to modify dictionary elements in Swift?

You can add elements of in dictionary by using subscript syntax . You need to include new key as the subscript index and assign a new value of the type as of Dictionary.

Example 6: Setting elements in a dictionary

 var someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") someDictionary("Japan") = "Tokyo" print(someDictionary) 

When you run the program, the output will be:

 ("Japan": "Tokyo", "China": "Beijing", "India": "NewDelhi", "Nepal": "Kathmandu")

In the above example, we've created a new key-value pair "Japan": "Tokyo" in the given dictionary by using the subscript syntax.

You can also use subscript syntax to change the value associated with a particular key as:

Example 7: Changing elements of a dictionary

 var someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") someDictionary("Nepal") = "KATHMANDU" print(someDictionary) 

When you run the program, the output will be:

 ("China": "Beijing", "India": "NewDelhi", "Nepal": "KATHMANDU")

Some helpful built-in Dictionary functions & properties

1. isEmpty

This property determines if an dictionary is empty or not. It returns true if a dictionary does not contain any value otherwise returns false.

Example 8: How isEmpty works?

 let someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") print(someDictionary.isEmpty) 

When you run the program, the output will be:

 false

2. first

This property is used to access the first element of a dictionary.

Example 9: How first works?

 let someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") print(someDictionary.first) 

When you run the program, the output will be:

 Optional((key: "China", value: "Beijing"))

3. count

This property returns the total number of elements (key-value pair) in a dictionary.

Example 10: How count works?

 let someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") print(someDictionary.count) 

When you run the program, the output will be:

 3

4. keys

This property returns all the keys inside the dictionary.

Example 11: How keys works?

 var someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") let dictKeys = Array(someDictionary.keys) print(dictKeys) 

When you run the program, the output will be:

 ("China", "India", "Nepal")

Similarly, you can use values to get all the values inside the dictionary.

5. removeValue

This function removes and returns the value specified with the key from the dictionary. Both key value pair will be removed from the dictionary.

Example 12: How removeValue() works?

 var someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") let val = someDictionary.removeValue(forKey: "Nepal") print(val) print(someDictionary) 

When you run the program, the output will be:

 Optional("Kathmandu") ("India": "NewDelhi", "China": "Beijing") 

Similarly, you can also use removeAll function to empty an dictionary.

Things to Remember

1. While using subscript syntax to access elements of an dictionary in Swift, you must be sure the key lies in the index otherwise you will get a nil value. Let's see this in example:

Example 13: Key must be present

 var someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") let val = someDictionary("Japan") print(val) 

When you run the program, the output will be:

 nil

In the above program, there is no key Japan. So when you try to access the value of the key "Japan", you will get a nil value.

2. Likewise, key-values are case-sensitive in Swift, so you must make sure the correct cased key/value is used. Otherwise, you will get a nil value. Let's see this in example:

Example 14: Keys are case-sensitive

 var someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") let val = someDictionary("nepal") print(val) 

When you run the program, the output will be:

 nil

In the above program, there is no key nepal. So when you try to access the value of the key "nepal", you will get a nil value.

3. There is also a way to provide a default value if the value for a given key does not exist. Let's see this in example:

Example 12: Default value for non-existent key

 var someDictionary = ("Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi") let val = someDictionary("nepal", default:"Not Found") print(val) 

When you run the program, the output will be:

 Not Found

Trong chương trình trên, chúng tôi đã chỉ định một giá trị Không tìm thấy trong tham số mặc định khi truy cập từ điển. Nếu giá trị không tồn tại cho khóa, giá trị mặc định được trả về nếu không giá trị được trả về.

Trong trường hợp của chúng tôi, khóa "nepal" không có, vì vậy chương trình trả về Không tìm thấy .

thú vị bài viết...