Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Using dictionaries

Converting values Преобразование значения | Writing if statements | Writing if statements Написание если заявления | Using the switch statement | Using the switch statement Использование Переключатель | Creating loops in Swift | Creating loops in Swift Создание петель в Swift | Defining functions | Defining functions Определение функции | Creating and using arrays |


Читайте также:
  1. A form of cryptosystem in which encryption and decryption are performed using the same key. Also known as conventional encryption.
  2. Answer the following questions using your own words but taking into account the
  3. C) Interview your partner using the questions in
  4. Choose a verb from the list and complete the text using Past Continuous or the Past Simple.
  5. Complete the following sentences using an appropriate form of the verb.
  6. Creating and using arrays
  7. Creating and using arrays Создание и использование массивов

 

- And the second built-in collection type in Swift is the dictionary. Depending on your language background, you may be familiar with the concept of this collection using the term Associative Array, or with Map, or by Hashtable, or, possibly, just Dictionary. Swift certainly isn't the only language that calls this kind of data structure a dictionary. So, the key difference: while a basic array stores multiple values, each one accessed with a zero-based sequence of integers, a dictionary, instead, stores multiple values, each one accessed using a unique key.

So, with a dictionary, we store sets of keys and values, each one being a key/value pair, and the key/value pairs are kept together. This key could be a string, or the key could be an integer. In fact, the key can be any kind of object. Unlike an array, the keys in a dictionary do not have to be in any specific order, as long as they are unique. We can't have duplicate keys in a dictionary. We can have duplicate values, if that makes sense for your data, but we can't have duplicate keys.

This example is US state as values, accessed using their state abbreviations as keys. Or we might have airport codes as keys and their corresponding cities as values, or product IDs as keys and the products they represent as values, but always key and value pairs that belong together. Just as with arrays, dictionaries in Swift are strongly-typed. That's not just one type but two, because, for any one dictionary, all the keys must be of a specific type and all the values of a specific type, although the type of the keys and the type of the values don't have to be the same.

So we could, for example, as on the left here, we could have a dictionary where all the keys are integers and all the values are strings, or a dictionary where all the keys are strings and all the values are Booleans, or a dictionary where all the keys are strings and all the values are also strings. But what we can't have is one dictionary where the key might be an Int or might be a string. That is not permitted. Over to Xcode, I have a new blank playground here. When creating a dictionary, as when creating any variable or constant or array, we must provide some kind of type information.

We either use type inference and let Swift do it, if the initial values are obvious, or we'd have to use an explicit type annotation. So, first, the shorthand way to do it: with a simple dictionary, we can use a dictionary literal; looks very similar to the array literal in that it's using square brackets around the entire contents of this. But what we're doing is not just multiple single values, but multiple key and value pairs. Each key and value pair have a colon between them, and they're separated with a comma.

So here, what I'm doing is going to be using type inference. All the keys and all the values provided are obviously strings, so this array will be automatically typed as such. I can use Quick Look to see inside this dictionary, that it is four sets of key/value pairs, and drill down inside to see that each one has two pieces. However, if I wanted to declare a dictionary without any initial values, so there's nothing to infer, and then, later, load it up with values, perhaps some external data, I would need to declare it with a type annotation.

For a dictionary, it needs two types: the type of the keys and the type of the values. This is the way we do it. Here, I'm declaring a variable dictionary called products that is of type. We use the square brackets, Int, colon string, a dictionary with integer keys and string values. As with arrays, I can use the square brackets, the subscript syntax, if you prefer, to access any one key/value pair. If I do a printline statement, like this, in a dictionary using the key AZ -- so I'm printing whatever's found using that key -- I'll get the value Arizona, though, if you see it over here, in the results pane, it has the word 'optional' around it.

We'll get into optionals two movies from now, but, in short, it's because any time I'm accessing a dictionary, I have to keep in mind the idea that maybe this key is in the dictionary and maybe it isn't, and this line would have had nothing to print. I can also use this same format, using the subscript syntax to either change or to add a new value. So, in this case, I'm saying states and I'm using FL as a key. That doesn't actually exist in the initial values that I provided for this dictionary. So, in this case, what will happen is, because FL didn't exist, it'll be added as a new key/value pair.

If it did exist, it would have tried to change the value. Dictionaries in Swift don't have an append method like arrays do, simply because with arrays, we can always guarantee that we can add a new item to the end of an array. We just let the array decide what index that item is. But we're not letting the dictionary tell us what index we have; we're controlling the key. So with a dictionary, we need to support the idea that we think we're adding a new key/value pair, but that key might already exist in the dictionary with a different value for it.

Now, using this subscript syntax here is the shorthand format. The equivalent longhand method for doing this is the updateValue method, so updateValue forKey. So states is the name of our dictionary. Dot updateValue, we pass in a value, and then we name the parameter for a specific key. If the key exists, we'd update a corresponding value, but if it doesn't, it would be added as a new key/value pair. If I wrote this code in a playground, this call to updateValue, I would expect to see nil in the results pane because, what updateValue does is, attempt to first retrieve and return any original value for this key, if one existed in the dictionary before it then updates that value.

Well, in my case, this key NV did not exist, so we get nil returned, nil in Swift simply meaning the absence of a value. On the other hand, if I write the same code, doing a updateValue, but where the key actually matches, then I will get the existing value returned before it's then updated. So, in this case, I'm trying to change the value for the key KY. That does exist. That was in the original version of this dictionary up here on line three, and I'm updating the value, but this will first return the original value for this, which was just the word Kentucky.

Let's take a look at the current state of this dictionary. I'll just write it on its own line, come over here and, in the Quick Look, click the eyeball here, and we can see that this is pretty much the sets of keys and values I would expect to see right now. Notice that they do not have to be in any specific order here. You might have created things in alphabetical order, but the way things have been added, that does not need to be kept in that way. Well, we've seen a place where we're using this word nil, and that's an important word when we're working with dictionaries because, talking of nil, the easiest way to remove a key/value pair from a dictionary is to use subscript syntax, using a particular key and then setting its value to nil.

So we're finding the key DE and setting equal to nil. Now, importantly, this does not mean that the key DE still exists in the dictionary, just has a nil value. This will remove the entire key/value pair from the dictionary. Then, if I wanted to verify that, I could put the word of that state after, use Quick Look, and we do not have DE with an empty entry; it's completely gone. The equivalent longhand method for doing this would be called removeValueForKey.

Again, despite the name, this doesn't just remove the value, it removes the entire key/value pair from the dictionary. Though, this one will also return the original value that might have been at that key position, in this case, California. Now, as with arrays, we can use the dot countProperty to find out the number of key/value pairs in the dictionary. In this case, there will be four states left after adding some and removing some others. And, finally, with dictionaries, we'll also want to be able to iterate over it, to step through every item.

We can also use the convenient for in loop to go through every key/value pair in a dictionary. Although the syntax does have one extra touch, because the item that we get each time around doesn't just have one piece of information, it will have a couple. It will have both a key and a value. So here, I've got this for in loop: for, individual item, in the state collection. Now, we've got them written inside parentheses here, key, comma, value, but these are actually temporary names for each time around the loop, and these names are up to us.

It'll be the key, then the value, but I could have actually just as easily written abbrev, comma, fullname. Whatever the first one is will be the key; we'd have to use that within the body of the loop. Whatever the second one is will be the value. So this will loop through all the key/value pairs in states. Then we got this four times option here. I could click the plus button, the value history button, to see the output. And this is exactly what I'd expect. There are four states left, AZ is short for Arizona, et cetera, et cetera.

So we're iterating very easily over the entire dictionary and getting to both the key and the value. It's a very easy, readable format. However, this simple-looking piece of syntax here, where we have two names enclosed in parentheses, we need to talk about this, because it represents our first, but not our last, encounter with a concept found in Swift but not found in many other programming languages, and that's the idea of a "tupple," or tuple... up next.

 

 


Дата добавления: 2015-08-20; просмотров: 82 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Creating and using arrays Создание и использование массивов| Using dictionaries Использование словарей

mybiblioteka.su - 2015-2024 год. (0.007 сек.)