Swift's Array and dictionary

Source: Internet
Author: User

Http://www.cocoachina.com/swift/20151230/14802.html

When it comes to arrays and dictionaries, as long as the process of the small partner is not unfamiliar. Arrays and dictionaries in Swift also have some bright features, and today's blog will look at the array and dictionary in Swift. or follow the previous style, when we introduce the arrays in swift, we compare the arrays and dictionaries in OBJC, because OBJC is also the primary language for iOS development. Whether it is a simple or complex program, arrays and dictionaries are more useful, although they are the foundation of Swift, but they are also important. For a collection class on OBJC, refer to the previous blog, "collection classes in Objective-c".

I. Arrays in SWIFT (array)

Arrays are present 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 their own characteristics. Swift is no exception, and the array used in Swift is more user-friendly.

1. Declaration and creation of arrays

Before I talk about array declaration creation in Swift, I want to talk about the declaration and creation of arrays in OBJC, below is how immutable and mutable arrays are created in OBJC. In OBJC, you can declare an immutable array using Nsarray, and use Nsmutablearray to declare mutable arrays.

1234 NSArray *objcArray01 = [NSArray array];     NSArray *objcArray02 = @[@(1), @(2)];          NSMutableArray *mutableArray = [NSMutableArray array];

In the swift language, you can use the keyword let to declare immutable groups, use Var to declare mutable arrays, and the code below declares several ways of changing arrays in Swift. One thing to note is that the array in the OBJC is allowed to store only objects inside, not to store basic data types (Int, float, etc.). In Swift, however, the base 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 types of data for the array elements, indicating that the array can only store the value of the int type, if you put other values in the inside, I'm sorry, the compiler will error.

In the swift array, if you do not specify the data type of the elements in the array when declaring the array, the array can hold data of different data types. If you specify that only one data type is allowed to be stored in the array, then if you store other data types in it, then it is your fault, and the compiler will give you an answer to your error. The following are the specific examples:

2. Operation of arrays

(1) Variable and non-variable groups

If you want to add, modify, or delete elements in the array, you need to define the array as a mutable array. If you define an array as an immutable group, but you do it again, it's your fault. Neither OBJC nor Swift will allow the high-cold "be" of the immutable array to be thrown in a wrong way. However, variable arrays are different, and you can make additional deletions to variable arrays.

Is the result of nsarray operation in OBJC, you can not modify the elements in Nsarray, that is to say, you have only read permission on the operation permission of Nsarray, no permission to write. If you want to read and write to the array, then you need to use the variable array nsmutablearray. Using Nsmutablearray will not cause an error because you have read and write access to it.

Variable arrays and immutable groups in Swift are ultimately the use of variables and constants, the Var and let keywords. You have read and write permissions on the variable, and you hold the reading permission on the constant. Below is a small example, essentially a let and var discussion, below is the Swift instance:

  

(2) Inserting elements

An example of how to insert an element into an array has been shown in the swift instance above. The method used in the insert element in Swift into an array and in OC is the same, except that the method is called differently. The code below inserts a value of "OBJC" into the position of index 1 in the variable array arraytest. The syntax is relatively simple, do not do too much to repeat.

1 arrayTest.insert("Objc", atIndex: 1);

(3) Addition of elements and arrays

You can use the Append function to append values to the trailing array. If you want to append another array to the rear of an array, you can use the + = operator to manipulate it. Using + = can connect arrays, which is an exciting feature of Swift. For details, see the example below:

(4) Removing elements

The above is added and the next step is to remove the element. In fact, the method names and usages of the array removed in Swift are very similar to the way the elements in the variable group are removed in the objective-c. Below is often used in the removal method, the usage is not difficult to understand the place, here is a simple chat on a mouth.

Void RemoveAll (): Removes all elements in an array, with an optional parameter, keepcapacity. If keepcapacity = yes, then after the array has removed the element, its storage space is still there, stored in the value, no need to allocate storage space for him. If keepcapacity=no, then the array's storage space will be recycled.

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

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, and if n = 1, remove the previous element at this point, the function is the same as the string Removefirst () function. If n = 3, the first 3 elements are removed.

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

Void RemoveRange (subrange:range): This function is more versatile, and it can move successive elements within the effective range of the divisor group. It needs a range parameter, and below is how this function is used, where the starting position of range is 1 and the end position is 2, which is to remove the element from index 1 to 2. You can see the hints in playground. Range (Start:1, end:2) represents the half open interval 1. <2.

3. Assigning an initial value to an array using the array constructor

In some scenarios we need to initialize each item in the array, that is, to assign an initial value to each item in the set. For example, we're going to use an array to record the company's quarterly sales, and when the array is initialized, we give the array 4 elements that have an initial value of zero. Next, use the array constructor to do something. The bottom is to assign an initial value to the array when the array is created.

Second, the dictionary in Swift (Dictionary)

The dictionaries and objective-c in Swift are not identical in syntax, but are used in much the same way. The dictionary holds key and value, which is the value pair. You can use key to remove value, and in PHP's powerful language, array and dictionary are just 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, the system is allocated well, and is the element in the array is the subscript from small to large arrangement. The key-value pairs in the dictionary are not in a fixed order.

1. Creation of dictionaries

In Swift, the creation of dictionaries and the creation of arrays is similar, which is one more key than the array item. Two dictionaries are created below, the first dictionary is the data type that specifies the 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 is not fixed, because the values in the read dictionary are in the form of key-value rather than subscript. These are all mutable dictionaries, because we use the var keyword to decorate it, and if you want to create an immutable group, we can create it using the Let keyword. About let to create a dictionary of content, here do not do too much to repeat, because only need to change the bottom of the Var.

    

2. Change the dictionary item and delete

(1) The value of the query dictionary (read)

We can take the key of the dictionary key to remove the value corresponding to the keys. The code below is the value of "fluffy" and "small yellow", respectively, as follows:

(2) The Traversal of the dictionary

It's not a bad thing to take only one value, but here's how the dictionary is traversed. Below is the traversal of all keys in the output dictionary mydog, the Keys property of the dictionary is to get all the key values in the dictionary.

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

123        key: Optional("黄2")        key: Optional("小黄")        key: Optional("大黄")

===============================================================================

This is to get all the keys in the dictionary, so here's how to get all the values in the dictionary, as shown in the following code:

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

123          value:黄2         value:小黄         value:大黄

===============================================================================

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

The output results are as follows:

1234567891011 元组:(2, "黄2")        key: 2        value: 黄2        元组:(3, "小黄")        key: 3        value: 小黄        元组:(1, "大黄")        key: 1        value: 大黄

(3) Modification of the dictionary

The modification of the dictionary elements is relatively simple, with two types below. The first is to assign a value to the value of key directly in the form of key, but this modification does not return the modified value, the code is as follows:

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

(4) Adding elements

Adding elements to an existing mutable dictionary is much simpler and can be assigned to value directly through key. In a mutable dictionary, if the key already exists, it becomes the value of the modified dictionary above. As you can understand, when you assign a value to value by key, if key exists, it overwrites the original key-value pair, and if it does not exist, it is added. Below is the statement that adds elements to the dictionary:

(5) Removing elements

Below is a method for removing 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:dictionaryindexIndexforkey. The specific usage is as follows, when the removed element succeeds, the deleted value is returned in the form of a tuple.

Swift's Array and dictionary

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.