Explore Swift Array and dictionary _swift

Source: Internet
Author: User


An array is an ordered list of values that store several of the same types. The same value that can appear multiple times in an array in a different location.
The swift array is specific. Unlike the classes in Objective-c's Nsarray and Nsmutablearray, he can store objects of any type without providing any information about the nature of the objects they return. In Swift, a particular array can store value types that are always explicit, either by explicit type annotation or by type inference, not necessarily by class type. If you create an array of annotation values, for example, you cannot insert any value other than the int value into the array. Swift arrays are type-safe and are always aware of what they might contain.



Array syntax



The type of the array is Array<sometype>, and one of the SomeType is the type that the array allows to store. You can also write an abbreviated form of an array of type sometype[]. Although the two forms are functionally identical, the shorthand form is preferred, and this guide is used when referring to an array type.



When it comes to arrays and dictionaries, as long as it is a small partner in the process of editing is not unfamiliar. The array and dictionary in Swift also have some bright features, and today's blog is a glimpse of the array and dictionary in Swift. Or the previous style, in introducing the array in swift, we compare the arrays and dictionaries in OBJC, because OBJC is also the main language of iOS development. Both simple and complex programs, arrays and dictionaries are more useful, both of which are fundamental to swift, but they are also important. For a collection class on OBJC Please refer to the previous blog "Objective-c Collection Class".



first. Arrays in Swift (array)



Arrays exist in other programming languages, and arrays are collections of a set of numbers. Although there are arrays in other programming languages, arrays in different languages have some features of their own. Swift is no exception, and the array used in Swift is more humane.



    1. Declaration and creation of arrays



Before we talk about the creation of the array declaration in swift, I want to talk about the declaration and creation of arrays in OBJC, and the way in which the OBJC and mutable arrays are created. In OBJC, you can use Nsarray to declare an immutable group and use Nsmutablearray to declare a mutable array.


 Nsarray *objcarray = [Nsarray array];
   Nsarray *objcarray = @[@ (), @ ()];
   


In the swift language, you can use the keyword let to declare an immutable group, use Var to declare a mutable array, and the following code declares several ways of a mutable array in Swift. One thing to note is that arrays in OBJC only allow objects to be stored inside, but not to store basic data types (Int, float, etc.). In Swift, the basic data type is allowed to be stored in an array, as shown in the code snippet below. The three definitions of the array are given below. The latter two give the array element a data type, which means that only the value of type int can be stored in the array, and if you deposit other values into it, I'm sorry, the compiler will make an error.






In the array of swift, if the array is declared without specifying the data type of the elements in the array, then data of different data types can be stored in the array. If you specify that only one data type is allowed to be stored in an array, if you store other data types in it, it is your fault and the compiler returns you to your error. The details are as follows:






2. Operation of Array



    (1) Variable and non-variable group



If you want to add, modify, or delete elements in an array, you need to define the array as a variable array. If you define an array as an immutable group, but you do it again, it's your fault. Neither OBJC nor Swift allowed the high Cold "Chinese" of the immutable group to make any moves, or they would throw a wrong. But the variable array is different, and you can add a check to the variable array.



The following figure is the result of the Nsarray operation in OBJC, you can not modify the elements in the Nsarray, that is, you have the right to operate the Nsarray only read permission, not write permission. If you want to read and write to the array, then you need to use the variable arrays Nsmutablearray. Using Nsmutablearray is not an error, because you have read and write permission to it.






Variable arrays and immutable groups in Swift are ultimately the use of variables and constants, namely, Var and let keywords. You have read-write access to variables, and you have permission to hold reading on constants. Below is a small example, essentially a discussion of Let and Var, below is an example of swift:






   (2) Inserting elements



The above Swift example shows how to insert elements into an array. The method used to insert elements into an array in swift and OC is the same, except that the method is invoked differently. The bottom code is to insert a value "OBJC" into the position of index 1 in the variable array arraytest. Grammar is simpler than to do too much to repeat.


 
 


   (3) Additions to elements and arrays



You can use the Append function to append values to the tail of the array. If you want to append another array to the rear of an array, you can use the + = operator. Using + + to connect arrays is also an exciting feature of Swift. For specific actions, see the example below:






    (4) Removal of elements



The above is added, and the next step is to get the removal element. In fact, the method name and usage of the array removal in Swift is very similar to the way in which the elements in the variable group are removed from the objective-c. In the screenshot below is often used in the removal method, the use of what is not difficult to understand the place, this simple chat on a mouth.



Void RemoveAll (): Removes all elements in an array, with an optional parameter, keepcapacity. If keepcapacity = yes, then the array removes the element and its storage space exists, storing the value in it, without having to allocate storage space. If Keepcapacity=no, then the storage space of the array will be recycled.



String Removeatindex (): Removes the element from the specified index and returns the removed element.



String removefrist (): Removes the first element and returns the element that was removed.



Void Removefirst (n:int): This function means to move several elements in front of the divisor group, and if n = 1, remove the previous element and the string Removefirst () function is the same. If n = 3, the first 3 elements are removed.



String removelast (): Moves the last element in the divisor group.






Void RemoveRange (subrange:range<int>): This function is more versatile, and it can move contiguous elements within the effective range of the divisor group. It requires a range parameter, and below is how the function is used, the range starts at 1, the end position is 2, or the element that removes the index from 1 to 2. You can see the hints in playground. Range (Start:1, end:2) represents the half open interval 1. <2.






  3. Use the array constructor to assign an initial value to an array



In some scenarios we need to initialize each of the items in the array, which is to assign an initial value to each item. Take a chestnut, for example we want to use an array to record the company's quarterly sales, and when we initialize the array, we initialize 4 elements with zero initial values. Next, use the array constructor to do something. The bottom is to assign an initial value to an array when the array is created.






 second. the dictionary in Swift (Dictionary)



In the dictionary of Swift and in Objective-c, the dictionary is not the same as the grammar, but the usage is similar. The dictionary holds keys and value, which is the key pair. The value can be retrieved by key, and in the powerful language of PHP, array and dictionary are one thing. In fact, the array is a special dictionary, the key of the array is its subscript, but this subscript does not need you to specify, by the system allocated well, and is the element in the array is the subscript from small to large arrangement. There is no fixed order for key-value pairs in the dictionary.



   1. Creation of dictionaries



The creation of dictionaries in Swift is similar to the creation of arrays, which is a key more than the item of an array. Two dictionaries are created below, and the first dictionary specifies the data type of key and value, and the second dictionary does not specify a fixed data type for the key value. It is easy to see from the playground that the data in the dictionary has no fixed data, because the values in the reading dictionary are in the form of key-value rather than subscript. The variable dictionaries are created below because we use the var keyword to modify it, and if you want to create an immutable group, we can create it using the Let keyword. About let create the content of the dictionary, do not do too much to repeat in this, because only need to change the Var of below to get can.






   2. The dictionary item additions and deletions change to check



(1) Query dictionary value (read)



We can retrieve the value of the key by using the key of the dictionary keys. The code below is to remove the "hairy" and "Little yellow" values, as follows:






(2) The traversal of a dictionary



Just take a value that's a lot of discomfort, here is a dictionary traversal method. Below is a traversal of all the keys in the output dictionary mydog, and the dictionary's key property is to get all the values in the dictionary.






The output of the preceding code snippet is as follows, and the output indicates that each value is an optional type of data:



Key:optional ("Yellow 2")
Key:optional ("Xiao Huang")
Key:optional ("rhubarb")



To get all the keys in the dictionary, here's to get all values in the dictionary, as shown in the following code:






The resulting values for the above code snippet output are as follows:


    Value: Yellow
     value: Small yellow
     value: Rhubarb    


The next step is to iterate over the entire item of the dictionary, and each item is traversed as a tuple. The contents of the tuple are (key, value). Through the tuple we can get the key and value of the dictionary by using the form of a tuple. The specific code looks like this:






The output results are as follows:


 Tuples: (, "yellow")
     key: 
     value: Huang
     Yuan Group: (, "small yellow")
     key: 
     value: Small yellow
     Group: (, "rhubarb")
     key: 
     


(3) Modification of the dictionary



The modification of the dictionary elements is relatively simple, with two kinds below. The first is directly to the key by the form of value assignment, but this modification will not return the modified value, the specific code is as follows:






If you want to return the modified original value when modifying the value, you need to use the Updatevalue (Forkey:) method to modify the element. The function can return the modified original value, as shown in the following example:






(4) Adding elements



Adding elements to an existing variable dictionary is much simpler, and you can assign values to value directly by key. In the variable dictionary, if the key already exists, it becomes the value of the modified dictionary above. It can be understood that, if the key exists, it overwrites the original key value pair, if it does not exist, if the key is assigned to value. Below is the statement to add elements to the dictionary:






(5) Removal of elements



The screenshot below is a way to remove elements from all dictionaries,



RemoveAll (): Removes all elements.



RemoveAll (Keepcapacity:bool): Removes all elements and, if keepcapacity is true, preserves the original storage space of the dictionary.



Removevalueforkey (key:hashable): This method removes the element by key.






Removeatindex (Index:dictionaryindex




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.