Swift getting started (5) -- Array (Array), swiftarray

Source: Internet
Author: User

Swift getting started (5) -- Array (Array), swiftarray
Set Definition

Swift provides two data structures for data storage, Array and Dictionary ). Their main difference is that the elements in the array are determined by the subscript, and the value of the data in the dictionary is determined by the Key of the data. In our opinion, the set is an array or dictionary.

Set Variability

We can define a set constant or set variable. Once defined as a constant, the length, content, and sequence of the set cannot be modified. For example, you cannot add new elements to an array defined as a constant.

Array Creation

Because the creation of variables in swift follows the syntax of "var variable name: variable type", the creation of arrays is ultimately an array type definition. There are three methods to define the array type:

var arrayOne:Array<Int> = [1,2,3]println("arrayLong = \(arrayOne)")var arrayTwo:[Int] = [1,2,3]println("arrayShort = \(arrayTwo)")var arrayThree = [1,2,3]println("arrayThree = \(arrayThree)")

The first is the complete definition of the Array type, that is, the Array keyword is added with a pair of angle brackets, and the type of the Array element is written in the brackets.

The second is the simplified definition of the array type, that is, the type of the array element is written in a pair of square brackets. This is equivalent to the first definition method.

When using these two methods to define an array, make sure that each element type in the array is the same; otherwise, a compilation error will occur.

The third method utilizes the type derivation feature of Swift. It should be noted that the value of the array is composed of square brackets, and the elements in the array are separated by commas. If square brackets are changed to parentheses, the compiler will not report an error (this will change to tuples), so be careful to avoid inexplicable errors.

In addition to the simplicity of writing, the third method also has the advantage that you do not have to ensure that each element type in the array is the same. Let's use the code to see what happens when multiple elements of different types appear in the unified array:

Var arrayThree = [1, 2, 3] println ("arrayThree = \ (arrayThree)") var arrayMixed = [1, "abc", true, 1.5] println ("arrayMixed = \ (arrayMixed)") // set a breakpoint before the end of this line // input print arrayThree and print arrayMixed in LLDB for debugging.

The following result is displayed:

([Int]) $R0 = 3 values {  [0] = 1  [1] = 2  [2] = 3}([NSObject]) $R1 = 4 values {  [0] = 0x0000000000000137 Int64(1)  [1] = "abc"  [2] = 0x00007fff7255e8a8 {    NSNumber = {      NSValue = (null)    }  }  [3] = 0x00000001006008a0 {    NSNumber = {      NSValue = (null)    }  }}

Therefore, it is not difficult to find that the arrayMixed Array can add multiple types of elements because it is derived as the Array <NSObject> type. Similarly, once the array type is determined, you cannot insert a value that does not belong to this type.

In my textbooks, the author puts forward that the append method of Array cannot be used for arrays without specifying types. However, after my tests, there is no such restriction. If you are interested, you can test it on your own. please correct me.

Access and modify the length of an array

You can use the read-only attribute count of the array to obtain the length of the array:

var arrayThree = [1,2,3]println("arrayThree.count = \(arrayThree.count)")
Null array judgment

You can use the read-only attribute isEmpty of the array to determine whether the array is empty. Of course, the same effect can be achieved by checking whether the count is 0, but the code is slightly longer.

var arrayThree = [1,2,3]if !arrayThree.isEmpty{    println("Array Three is not empty")}
Add new elements

There are two ways to add new elements at the end of the array:

// Method 1: Use the array append function var arrayThree = [1, 2, 3] arrayThree. append (4) println ("arrayThree = \ (arrayThree)") // method 2, using the addition operator var arrayThree = [1, 2, 3] arrayThree + = [4] println ("arrayThree = \ (arrayThree )")

Either method is used, the newly added elements must be of the same type as the array. For example, adding the element '1. 5' to the arrayThree will cause a compilation error.
We can see that the essence of the second method is to call the addition operator between two array objects. The result is the result after the two arrays are spliced. Therefore, the second method has a powerful function, that is, adding multiple elements to the end of the array.

Another common method is to call the insert (atIndex :) method of the array to insert new elements at the specified position.

var arrayThree = [1,2,3]arrayThree.insert(4, atIndex: 2)println("arrayThree = \(arrayThree)")
Delete array elements

You can call the removeAtIndex () and removeLast () Methods of the array.

var arrayThree = [1,2,3]var numberThree = arrayThree.removeAtIndex(2)var numberTwo = arrayThree.removeLast()

The two methods will return the value of the deleted element. If you do not need to know it, you can ignore its return value and directly call the method.

Note that the removeAtIndex method must first determine whether the subscript is out of bounds, that is, it will use the length of the array. This means that the array needs to be traversed linearly. Therefore, if you only need to remove the last element of the array and the length of the array is large, you should use the removeLast () method.

Access array elements

After learning how to add and delete elements, we need to find a way to retrieve the newly added elements. You can use the array subscript to access the array elements at the specified position. The syntax is the same as that in C.

var arrayThree = [1,2,3]println("ArrayThree[2] = \(arrayThree[2])")
Modify array elements

Subscripts can not only access array elements, but also modify array elements. This is very similar to accessing array elements, as long as the positions of variables on both sides of the equal sign are exchanged.

Var arrayThree = [1, 2, 3] var secondInt = arrayThree [1] // access element var newSecond = 4 arrayThree [2] = newSecond // modify the array element

In addition, you can also modify the elements in batches using the array Subscript:

var arrayThree = [1,2,3]var firstNumber = 1var secondNumber = 2arrayThree[0...1] = [firstNumber,secondNumber]

At this time, the right side of the equal sign must be the array literal, rather than an array variable. That is to say, this statement is incorrect:

Var arrayThree = [1, 2, 3] var newArray = [3, 4] var newSlice: ArraySlice <Int> = [3, 4] arrayThree [0... 1] = newArray // error. ArrayThree [0... 1] = newSlice // correct

The reason is that arrayThree [0... 1] It is actually a SubArray. In Swift, its type is called ArraySlice, that is, an Array slice of the Int type, and an Array type variable on the right. According to the secure features of the Swift type, such operations are naturally prohibited.

What happens if the slice length on the left is different from the variable length on the right? Don't worry too much. This will not produce any errors. Swift will help us solve this problem intelligently.

var arrayOne:[Int] = [1,2,3]var arrayTwo = [1,2,3]var sliceOne:ArraySlice<Int> = [1,2,3]var sliceTwo:ArraySlice<Int> = [1]arrayOne[1...2] = sliceOnearrayTwo[1...2] = sliceTwoprintln("arrayOne = \(arrayOne)")println("arrayTwo = \(arrayTwo)")

The output results are as follows:

arrayOne = [1, 1, 2, 3]arrayTwo = [1, 1]

Therefore, if the variable length exceeds the slice length, an element (like arrayOne) is automatically added after the slice position, which is equivalent to calling the array insert (atIndex :) method several times. Similarly, if the variable length is less than the slice length, the element with no value is automatically removed, and the subsequent element is automatically added forward. The removeAtIndex () method of the array is called several times.

Although this will not cause any errors, we should avoid variable lengths at both ends of the equal sign for logic rigor.

Array Traversal

Previously, we introduced the addition, deletion, and modification operations for arrays, but there is still a missing search. That is, the traversal of the array. In Swift, apart from defining a subscript variable like a C language, traversing the array in a for loop also has two ways to traverse the array.

// Method 1: Use the for in loop to quickly traverse var array = [, 99] for number in array {println ("number = \ (number )")}

By observing the output results, we can find that the for in loop traverses the array in the order of forward and backward.

// Method 2: Use the enumerate function var array = [, 99] for (index, value) in enumerate (array) {println ("value = \ (value )")}

The returned value of the enumerate (array) method is an array. Each element in the array is a binary. The first value is the subscript index, and the second value is the value of the element. This method also traverses arrays sequentially.

Array Initialization

At the beginning of this chapter, we use the array literal to initialize an array. In fact, there are other initialization methods for arrays.

First, the constructor of the string is var String = string (). We can know the other two constructor methods of the array.

Var arrayOne = [Int] () var arrayTwo = Array <Int> () println ("the number of first Array elements is \ (arrayOne. count) ") println (" the number of elements in the second array is \ (arrayTwo. count )")

Running result:

The number of elements in the first array is: 0. The number of elements in the second array is: 0.

In addition, an array has a special constructor that can specify the length of the array. In this case, you must also specify the value of each element in the array. If you think it is useless, you can set it to 0 first and then modify it.

Var arrayThree = [Int] (count: 5, repeatedValue: 0) var arrayFour = Array <Int> (count: 5, repeatedValue: 0) var arrayFiver = Array (count: 5, repeatedValue: 0) print ("the third array is: \ (arrayThree)") print ("The fourth array is: \ (arrayFour)") print ("The Fifth array is: \ (arrayFiver )")

Thanks to the type derivation, the fifth array initialization method is also valid. However, the previous standard initialization method cannot be so simplified. The output result is as follows:

The third array is: [0, 0, 0, 0, 0] The fourth array is: [1, 1, 1, 1] The Fifth array is: [2, 2, 2, 2]
Full column in the appendix-Quick Start

[Swift entry (1)-basic syntax]
[Swift entry (2)-character and string]
[Swift entry (3) -- Tuple )]
[Swift entry (4) -- Optionals and Assert )]
[Swift entry (5) -- Array )]
[Swift getting started (6) -- Dictionary )]

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.