Swift programming language Learning 3.1 permutations

Source: Internet
Author: User

The Swift language provides classic array and dictionary collection types to store collection data. Arrays are used to store the same type of data sequentially. The dictionary, while storing the same type of data values in disorder, needs to be referenced and addressed by a unique identifier (that is, a key-value pair).

The types of data values stored in the array and dictionary in the Swift language must be understood. This means that we cannot insert the wrong data type. At the same time it also shows that we are fully confident about the type of value we get. Swift's use of explicit type collections ensures that our code is well aware of the types of work required, and allows us to find out the type mismatch errors in development early on.

Attention:

Swift's array structure exhibits different characteristics relative to other types when declared as constants and variables or passed into functions and methods. For a lot of other information, see the section on the variability of collections and the behavior of collections in assignment and replication.

Array

Arrays store the same type of multiple data using an ordered list. The same value can be present in different positions of an array multiple times.

The Swift array has detailed requirements for storing data. Unlike Objective-c's Nsarray and Nsmutablearray classes, they are able to store instances of whatever type and do not provide whatever essential information they return to the object. In Swift, a data value must be understood by the type before it is stored in an array, by means of an explicit type callout or type, and not by the class type. For example, suppose we create an array of int value types, and we cannot insert any data that is not of type int. Arrays in Swift are type-safe, and the types that are included in them must be understood.

Simple syntax for arrays

The write Swift array should follow a form like array<sometype>, where SomeType is the only data type in the array that agrees to exist. We can also use the simple syntax like sometype[]. Although the two forms are functionally identical, they are recommended for shorter types and are used in this article to use arrays.

Array Construct statement

We can use literal statements to construct an array, which is a simple way to construct an array with one or more numeric values. A literal statement is a series of values that are cut by commas and included by square brackets. [Value 1, Value 2, value 3].

The following example creates an array called Shoppinglist and stores a string:

var shoppinglist:string[] =["Eggs", "Milk"]//Shoppinglist has been constructed and has two initial entries.


The shoppinglist variable is declared as "an array of string value types", as string[]. Since this array is specified to have only a data structure of string, only the string type can be accessed. Here, the shoppinglist array is constructed from two string values ("Eggs" and "Milk") and is defined by a literal statement.

Attention:

The shoppinglist array is declared as a variable (Varkeyword created) instead of a constant (let creation) because many other data items may be inserted later.

In this example, the literal statement consists of only two string values. Matches the variable declaration of the array (only the array of strings), so the literal statement's allocation process is to agree to construct the shoppinglist with two initial entries.

Because of the type-judging mechanism of Swift, we do not have to define the type of the array clearly when we construct a literal statement that only has the same type of value array. Shoppinglist's structure can also be written like this:

var shoppinglist = ["Eggs", "Milk"]


Because the values in all literal statements are the same type, Swift can determine that string[] is the correct type of variable in the shoppinglist.

Access and change arrays

We are able to access and modify arrays by using the methods and properties of the array, or by following the banner method. You can also use the array's read-only property count to get the number of data items in the array.

println ("The shopping list contains\ (shoppinglist.count) items.") Output "The Shoppinglist contains 2 items." (This array has 2 items)


Use the Boolean key IsEmpty as a shortcut to check whether the value of the Count property is 0.

If Shoppinglist.isempty {   println ("The shopping list is empty.")} else {   println ("The shopping list was not empty.") )}//print "The shoppinglist is not empty." (The shoppinglist is not empty)



You can also use the Append method to add new data items after the array:

Shoppinglist.append ("flour")//Shoppinglist now has 3 data items, someone is in a pancake


In addition, the addition assignment operator (+ =) can also be used to add data items directly behind the array:

Shoppinglist + = "baking Powder"//Shoppinglist now has four items


We can also use the addition assignment operator (+ =) to directly join an array that has the same type of data.

Shoppinglist + = ["Chocolatespread", "Cheese", "Butter"]//shoppinglist now has 7 items


The ability to directly use subscript syntax to get the data items in the array, placing the index value of the data item we need is placed directly in the square brackets of the array name:

var FirstItem = shoppinglist[0]//The first item is "Eggs"


Note that the first item in the array has an index value of 0 instead of 1. Array indexes in Swift always start from zero.

We can also use subscripts to change the corresponding data values for an existing indexed value:

Shoppinglist[0] = "Six eggs"//The first item is now "Sixeggs" instead of "eggs"


You can also use subscripts to change a series of data values at once, even if the number of new and original data is different. The following examples replace "chocolate Spread", "Cheese", and "Butter" with "Bananas" and "Apples":

SHOPPINGLIST[4...6] = ["Bananas", "Apples"]//shoppinglist now has six items


Attention:

We cannot use the following banner to add a new item to the end of the array. Let's say we try to retrieve data from an index that is out of bounds or set a new value, we'll throw an execution-time error. We are able to compare the index value and the Count property of the array to verify that it is valid before using an index. Except when Count equals 0 o'clock (which indicates that this is an empty array), the maximum index value is always count-1, since the array is indexed 0.

Call the array's insert (Atindex:) method to include the data item before a detailed index value:

Shoppinglist.insert ("Maplesyrup", atindex:0)//Shoppinglist now has 7 items//"Maple syrup" is now the first item in this list


This time the Insert function calls the new data item with the value "Maple syrup" into the first position of the list, and uses 0 as the index value.

Similarly, we can use the Removeatindex method to move an item in an array. This method removes the data item stored in the array at a particular index value and returns the removed item (which we can ignore when we don't need it):

Let Maplesyrup =shoppinglist.removeatindex (0)//data item with index value 0 removed//shoppinglist now has only 6 items and does not contain maplesyrup// The value of the Maplesyrup constant equals the value of the data item being removed "Maple syrup"


When a data item is removed, an empty item in the array is actively filled by itself, so now the value of the data entry with index value 0 is again equal to "Six eggs":

FirstItem = shoppinglist[0]//FirstItem is now equal to "Sixeggs"


Suppose we just want to remove the last item in the array, we can use the Removelast method instead of the Removeatindex method to avoid the need to get the Count property of the array. Just like the latter, the former also returns the data item that was removed:

Let apples = shoppinglist.removelast ()//The last item of the array is removed//shoppinglist now only has 5 items, values that do not contain cheese//apples constants are now equal to "apples" strings


Traversal of an array

We can use the for-in loop to iterate through the data items in all the arrays:

For item in Shoppinglist {   println (item)}//Six eggs//milk//flour//baking powder//Bananas


Suppose we need the value and index value of each data item at the same time, we can use the global enumerate function for array traversal. Enumerate returns a set of key-value pairs consisting of index values and data values for each data item. We can break this key value pair into a transient constant or variable to traverse:

For (index, value) inenumerate (shoppinglist) {   println ("Item \ (index + 1): \ (value)")}//item 1:six eggs//Item 2:MI lk//Item 3:flour//Item 4:baking powder//Item 5:bananas


Many other introductions about the for-in cycle are shown in the For loop.

Create and construct an array

We can use the construct syntax to create an empty array of specific data types:

var someints = int[] () println ("Someints is of type Int[]with \ (someints. count) items. ")//print" someints isof type int[] with 0 items. "(Someints is an array of int[for 0 data items)


Note that someints is set to the output of a int[] constructor, so its variable type is defined as int[].

In addition, assuming that the type information is provided in the code context, such as a function argument or a constant or variable of a defined type, we can create an empty array using an empty array statement, which is very easy:[] (a pair of empty square brackets):

Someints.append (3)//Someints now includes an int value someints = []//someints is now an empty array, but still a int[] type.


The array type in Swift also provides a constructor that creates a specific size and that all data is default. We are able to pass in the array constructor the number of data items (count) and the appropriate type (Repeatedvalue) that are ready to increase the new array:

var threedoubles = double[] (count:3,repeatedvalue:0.0)//Threedoubles is an array of double[], equal to [0.0, 0.0,0.0]


Because of the existence of type judgments, we do not need to specifically specify the data types stored in the array when using such a construction method, because the type can be judged from the default value:

var anotherthreedoubles = Array (count:3,repeatedvalue:2.5)//Anotherthreedoubles is inferred asdouble[], and equals [2.5 , 2.5, 2.5]


Finally, we can use the addition operator (+) to combine two existing arrays of the same type. The data type of the new array is judged from the data type of the two arrays:

var sixdoubles = Threedoubles +anotherthreedoubles//sixdoubles is judged as double[], equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]


Swift programming language Learning 3.1 permutations

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.