Читайте также:
|
|
- Instead of always working with single values, one at a time, we want to start grouping multiple values together into collections. Swift has two fundamental built-in collection types, the Array and the Dictionary. More complex data structures can certainly be attained by linking two additional frameworks, but the Array and Dictionary are part of the Swift languages itself. So, that's what we'll cover first. Okay so first up, Arrays, the most common collection type across every programming language on the planet, an ordered collection of items.
So, there's a few basic rules before we make one. Arrays are zero-based in Swift, as you'd probably expect from a C influenced language. We start at index zero and we go up one by one. Next, Arrays are typed safe in Swift, meaning we create Arrays of specific types. We create an Array of Ints or an Array of Strings or an Array of (Bous). You don't mix and match your Array of elements. The big benefit of this is that you always know what you're going to get, when you index into a particular Array, because it is typed.
That's unlike the typical behavior in Objective-C, where an NS Array could hold any kind of object at any position, and you often had to write code to figure out or at least confirm, that what you just pulled out an Array is what you thought it was. We don't have to worry about that here. One thing you might be wondering is are Swift Arrays dynamic, are they changeable, are they mutable, or re-sizable, whatever term you prefer to use. That depends. It simply comes down to whether you use the keyword Var or Let when you declare the Array.
If you used Var, your Array is a variable. It's mutable, changeable. You can add to it, delete from it, change elements at any position. If you used Let, your Array is an immutable constant. Once you've provided the initial state for that Array, the initial value's, it's fixed You can't add to it, and you can't alter those elements. So, how do we make one? Over to (X-curt 6), I've created a new playground file and here's the simplest format. I'm going to make a basic Array of Integers and make it as a constant. So, I'm providing a few initial values.
There's a couple of things going on here. One is I'm using these square brackets to provide this comma separated list of Integers. This is the shorthand Array literal format in Swift. I could also use these square brackets to create an Array of Strings, for example. In this case, it's a variable Array, because I'm using Var. In both cases, we have type inference happening here. These values are so obviously Integers here, and they're so obviously Strings here, the type is inferred. I don't need a type annotation, but make no mistake, what we get is a strongly typed Array of Integers, and a strongly typed Array of Strings.
If try to make an Array with multiple types at the same time, I'm going to get a compile error, which in X-code will show up as soon as it's detected. So, while these two Arrays have had their types inferred, as with variables, if I wanted to declare an Array, but I can't or don't want to immediately provide values for Swift to and for, then I will need a typed annotation. So, let's say I want to declare a variable Array of Strings, but not give it some initial values. If I want to (mumbling) just a variable that was a String, I'd do something like this.
Flavors:String. Flavors is of type String. That's a regular String variable. I need a variable that's (sub) the typed Array of Strings. I just surround the type with the square brackets. That's how we declare an Array type. My Var flavors is of type Array of String. Now, I can set some initial values for that. I can use the Array literal format. This is going to set the first three elements to these Strings. When it comes time to access these elements, as in many languages, I can use the square brackets with a particular Integer index to directly access any elements.
The first flavor is accessing the zeroth element of the Array, which will tell me vanilla. I can use the same format if I want to change the value at that location. This is permitted because, again, this is a variable Array I can change each element at each index point. As this is variable, I can also add elements to the Array. Here I'm using the append method to add to the end of the Array. Again, this is type, so I can only add Strings. If I try to add an Integer, or a Bouillon, or anything else, we'd get a compile error.
Having said that in Swift, you can also use the shorthand of the plus equals operator to append a new Array element. Although this plus equals can also be used for adding numbers, or concatenating Strings together. To avoid confusion, you must use the square brackets around this new element to make it very clear, that when someone's reading this code, we're adding an Array element. We're not just changing a single String variable. However, if you wanted to insert a new element not right at the end, not appending to the end of the Array, but at some other specific position, then, it's the insert method of the Array which we can use, which takes two pieces of information.
First, the new value that we want to add. Second, the index position. What locations you want to put this at? I'm going to put at three. Although, it's going to complain about this, because the index must be written as a named perimeter in Swift. I do have this little compile flag popping up. If I click that, it'll tell me there's a missing argument label at index. There's even a fix it, which X-code will suggest, and I can let it do that. I'll just highlight that and and either click it or press return. It inserts that named argument option for me.
Now, as we're starting to have a few more items in this Array, I want to see what its current status. I could write the name of the Array on it's own line, this is a good way to see it. We can see some of this information, if I had a larger screen I would be able to see more of it. I can mass over and let it give me the pop-up. Another option is to come over and find the eyeball. This is the quick look icon. By clicking that, it lets us look inside more complex objects that can't be easily shown in the results pane. In this case, to show us what our Array looks like and we can click this at every point along the way.
Highlighting quick look up here, we only have three elements. Highlighting down here, we have six. If this was an Array of objects, we'd get a further quick look icon inside each element that would let us drill down even further inside those. All right, so that's adding. Well there is also the ability to remove items. We can use the remove last or remove at index methods to delete item from the Array. One very typical requirement is to find out how many elements an Array has.
In Swift, that's us using the count property. I'll just use dot syntax to get to this. So, printing that the Array has how ever many items daysinmonth.count. That's the Array that I created up at the top here on line three. For having said that, if I'm checking for an Array that's empty, I could check for an account of zero, but there is also a built-in is empty Bullion property that I can test, which makes for more readable code. So, if daysinmonth. is empty, we have nothing in the Array.
Now, when we have collections, we want to be able to go through the entire thing to iterate over every item. We could certainly use a standard C style for loop or a while loop to do this keeping track of an index. It is far easier in Swift to use a for-in loop. We don't even have to worry about index numbers. We can just automatically go through every item in the Array, however many that is. So, the general format of doing that is it for individual item in some kind of collection. We have an Array collection called daysinmonth.
So, that's our collection name. For each item, well, it's up to us. What do we want to call each individual part. Well, I might as well us a name that means one individual element of this Array. So, I'll just use month. So for month in daysinmonth, we need to close that code brace. Now, remember Arrays are tight in Swift, so if I write a for-in loop that iterates over an Array of Ints, which is what I'm doing here, then whatever name I use here, in this case month, will represent every Int in the Array one by one.
If I wrote a for-in loop that iterates over an Array of Strings, then this name would represent each String in the Array. That's it. That's all we need to do to go through the Array. No worries about indexes or fence posts arrows, it just works. I see over here that we've got 12 times. It showing me that there's 12 items in this Array. So, we went through the loop 12 times. If I wanted to see actually happened, I'll mouse over to the value history button in the playground, click that. It's going to open the third section, and we'll actually see the output from here, both the print-line statements.
The first flavor is vanilla. The Array has 12 items, and then each individual item being printed from that loop, each one on its own line. All right, so this is the basics of working with Arrays. Really, the last few minutes have not just been the core ideas of working with Arrays, but the core ideas of working with any collection in Swift. So, let's take a few of these ideas and see the other built-in Swift collection type.
Дата добавления: 2015-08-20; просмотров: 119 | Нарушение авторских прав
<== предыдущая страница | | | следующая страница ==> |
Defining functions Определение функции | | | Creating and using arrays Создание и использование массивов |