Spy on Swift's array safe index and array slices

Source: Internet
Author: User

Arrays and dictionaries in Swift are very common, and arrays can be indexed by index to query the elements, and dictionaries can get the corresponding values by key subscripts. When using arrays, a common fatal error is that arrays are out of bounds. If the array is out of bounds in your application, then I'm sorry if the program's temperament would crash. To prevent crashes, we do some safe handling of the collection. For example, an array is extended to carry out security checks on the index of a group, ensuring that the index of the arrays is within the normal range. In the objective-c is also often the array, dictionaries and so do some processing operations.

The main content of today's blog is to introduce the security extensions of the common collections in objective-c , and to look at the processing in swift language. It also introduces a custom subscript in Swift, in which the custom subscript actually accesses an object by means of subscript and a specific subscript value. Custom subscripts are very useful in some situations. Then the concept and the practical way of slicing are also given below. Talk less about getting into today's theme.

A safe Index collection element

It is necessary and often practical to conduct a security check on a collection index, the most common being security checks on arrays and dictionary indexes, which is an analogy to the security checks of array indexes in this objective-c to augment the array of Swift. This allows your swift array to also have the ability to log group security checks.

  1. Nsarray Security extensions to indexes in Objective-c

The code below is very simple, it is an extension to the Nsarray in objective-c , which is located in the Nsarray related extensions. In your project, if you add this extension code, you can safely index the array using the Objectatindexsafe: method. It is not difficult to see the code when defining the function parameter, we declare the index as Nsuinteger, which is a positive integer, which excludes you from passing a negative number to the subscript. The legitimacy of index is then verified and nil is returned if index is not within the range of the array's validity. When the element you are looking for does not exist, your return to nil will not cause the program to crash, because Nil's address is 0x0, which is similar to zeroing if referenced.

Of course, below is just nsarray security extension one of the methods, there are many extended security methods, such as the array of additions and deletions can be extended to the corresponding security extension, the expansion of the way and ideas and the following simple code similar, again do not spend too much space to introduce it.

1 -(ID) objectatindexsafe: (Nsuinteger) Index {2     if (Index > self.count-1) {3         return  nil; 4     }5     return  [self objectatindex:index]; 6 }

  

Security extension to array in 2.Swift

The above simple introduction to the security methods in Objective-c, even if it is a swift-related content, the following will give the swift language similar method. I'll try to be more specific when it comes to Swift, because this blog is primarily about swift content. Next, use the Swift language to re-secure the nsarray array index Security validation method above objective-c. Of course, the rewritten content is also very easy to understand.

(1) The subscript method is mainly overloaded, in the overloaded subscript method, the range of index is checked by the three mesh operator. If index is in 0.. <count this half-open interval, the value of the current index is returned, and nil is returned if it is not in that range, and below is the security check for the array index.

1 extension Array {2     subscript (safe index:int)-Element?  {3         return (0: <count). Contains (index)? Self[index]: nil 4     }5 }

    

(2) The above is a safe index extension of the array in Swift, followed by simple use, the code snippet below is a test of the above security extension function. First, an array testarray is created, an index array indexs is created, and the element values in the Indexs are traversed, and the Testarray is retrieved as the Testarray subscript. Of course, when retrieving, we use the safe method defined above, and there is an illegal subscript in the Indexs subscript array. In this case, let's verify our security approach.

In the array traversal, of course, we use the for-in loop to remove each index from the Indexs and then use the Guard statement to remove the value from the Testarray. Use the Guard statement to filter out the nil value returned because of the illegal index. The specific code snippet is as follows:

The above code snippet is not difficult to understand, the running results of the above test code are as follows, from the running results can be a good explanation of the problem, and when the index is illegal, will not crash, and reasonable to give the corresponding error prompt, see the specific results below.

The above extension can also be extended by the entire collection type, that is, collectiontype , but when the collectiontype is extended, the Index is used The where clause is limited so that Index must conform to the comparable protocol, as shown below, although the following method is less used because the array is typically out of bounds, Because in the dictionary, if you index the value of a nonexistent key, it returns a nil value without crashing. But in the array, you index the nonexistent index and throw an error. Below is another way to deal with it, but it is less used in this way.

After the implementation is extended, the safe method can also be used in the array.

  

Second, use multiple index subscript array

The extended function is very powerful, and this section will give the extension of the other array. The function of this extension is that you can set values for the array through multiple indexes, and get the values of multiple arrays at once through multiple indexes. The feature is very powerful, and the next step is to implement the feature.

  1. Learn about the zip () function and zip2sequence

When implementing multiple index extensions for an array, you need to use the zip () function, the zip () function to receive two sequences, and return a zip2sequence type of data. What exactly does the zip () function do? The zip () function is then done with a small instance. First look at the description of the zip () function on the Apple help document. The following are the specific examples:

The English meaning of the above is probably "to construct a sequence pair based on two basic sequences, in sequence pairs, I pairs, which represent the element I of each basic sequence." "in the process of defining the zip function, we can see that the zip () is a generic function that receives two parameters of type Sequencetype and then returns a zip2sequence type of data. The newly created sequence pair exists in the zip2sequence. Say so much or a little demo. Affordable, with a small example, see the use of the zip () function at a glance.

(1) Create two arrays of zip1 and ZIP2, combine the two arrays as parameters of the zip () function and merge two arrays. The specific implementation is as follows:

(2) through the above program can be seen, Zipsum is a zip2sequence<array<int>, array<int>> type of constant, we can use dump () to print the Zipsum constants, Observe the data storage structure in which the structure is as follows:

The output is as follows, as the result is easy to see, there are two elements in the sequence, the first element corresponds to the array zip1, and the second element corresponds to the array zip2.

(3) The next step is to traverse the zipsum sequence through the for-in loop, which is the code that iterates over the zipsum.

The results of the above-zipsum traversal are as follows, as the output below shows that the output is a pair traversal, and if the elements in an array are superfluous, they are ignored.

2. Extension implementations of multiple indexes on arrays

In this extension to be implemented, we extend the array by overloading the subscript method in an extension so that it can accept multiple subscripts, index the values corresponding to multiple subscripts, and make an array of index results. In the subscript method, the corresponding value of the index is obtained by the get method, and the corresponding index value is set by the set method. The code snippet below is the implementation of this extension:    

1 extension Array {2Subscript (I1:int, I2:int, rest:int ...)[Element] {3         //get the corresponding value in the array by implementing the Get method4         Get {5             varResult: [Element] =[Self[i1], Self[i2]]6              forIndexinchRest {7 result.append (Self[index])8             }9             returnresultTen         } One          A         //set the corresponding index of an array by using the Set method -         Set(values) { -              for(Index, value)inchZip ([I1, I2] +rest, values) { theSelf[index] =value -             } -         } -     } +}

In the above-mentioned extension of the implementation, there is not much difficulty in the place. In subs two cript functions, variable parameters are used, and the number of subscript function parameters is more than two (including two). This is then done by traversing the zip () function and the result set returned by the ZIP () function to set the value for multiple subscript indexes. With this extension, we can operate on multiple index arrays. The above extensions are used in the following ways:

Three, array slicing

Array slicing also does not exist in OC, which is a new concept introduced by Swift, which will discuss the usage and characteristics of array slices. Below, let's look at how to generate an array slice with a small demo. The code snippet below first converts a string through the map function into an array arraytest, and then we create a slice of the array. The code snippet below creates a slice in the range of subscript 3 to subscript 6 in the arraytest array, arrayslices is the array tile variable, which is arrayslice<string> type, as shown in the following code snippet.

One thing to note in an array slice is that the subscript of the array slice is consistent with the subscript in the original array. If you want to remove the first value in the slice arrayslices, we want to use arrayslices[3] instead of arrayslices[0], if you use Arrayslices[0] you will get an error, as shown below:

  

Because the array is a value type, although the slice has a corresponding array subscript to the original array, but the slice is a partial copy of the original array, modifying the slice or modifying the original array does not affect each other, and the example below shows the test as follows:

   

If you convert a slice to an enumeration, then the subscript relationship in the slice that corresponds to the original array will not exist, with the tiles converted to an enumeration sequence and then traversed with the following code:

The code snippet above shows the following output:

Today the blog is written here, there are many extensions to the array, there is a chance to discuss later. In fact, we can also add subscripts to our own objects in a number of ways. That is, the object properties can be accessed by subscript, which is discussed later.

Spy on Swift's array safe index and array slices

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.