Ios swift learning diary 5-set type

Source: Internet
Author: User

Ios swift learning diary 5-set type

The Swift language provides two Collection types, classic array and dictionary, to store the set data. Arrays are used to store data of the same type in sequence. Although the dictionary stores the same type of data values unordered, it must be referenced and addressable by unique identifiers (that is, key-value pairs ).

The data value types stored in arrays and dictionaries in Swift must be clear. This means that we cannot insert incorrect data types into it. At the same time, this also shows that we can be very confident in the type of the obtained value. Swift's use of explicit type sets ensures that our code is very clear about the types required by our work, and allows us to find any Type Mismatch Errors early in development.

Note:

The array structure of Swift is different from other types when declared as constants and variables or passed functions and methods. For more information, see the set variability and set behavior in assignment and replication.

Array

Arrays use ordered lists to store multiple data of the same type. The same value can appear multiple times in different positions of an array.

Swift arrays have specific requirements on data storage. Unlike Objective-C'sNSArrayAndNSMutableArrayClass, they can store any type of instances and do not provide any essential information about the objects they return. In Swift, the data value type must be clear before it is stored into an array by explicit type annotation or type inference, and is not requiredclassType. For example, if we createIntValue Type array. We cannot insert anyIntType of data. Arrays in Swift are type-safe and must contain clear types.

Simple array syntax

To write the Swift array, follow the following steps:Array In this form, whereSomeTypeIs the only allowed data type in this array. We can also use an imageSomeType[]Such a simple syntax. Although the two forms are the same in terms of functionality, we recommend the shorter ones, and this form will be used in this article to use arrays.

Array Construction statement

We can use literal statements to construct arrays. This is a simple method to construct arrays with one or more values. A literal statement is a series of numeric values separated by commas and enclosed by square brackets.[value 1, value 2, value 3].

In the following exampleshoppingListAnd stores the string array:

Var shoppingList: String [] = ["Eggs", "Milk"] // The shoppingList has been constructed and has two initial items.

shoppingListThe variable is declared as an array of the string value type.String[]. Because this array is specified to onlyStringA Data Structure, so onlyStringType can be accessed. Here,shoppinglistThe array consists of twoStringValue ("Eggs"And"Milk"Is constructed and defined by a literal statement.

Note:

ShoppinglistThe array is declared as a variable (varKeyword creation) instead of constants (letIt is created because more data items may be inserted later.

In this example, the literal statement only contains twoStringValue. Variable declaration matching the Array (can only containStringSo the allocation process of this literal statement is to allow two initial items to be constructed.shoppinglist.

Due to the type inference mechanism of Swift, when we use literal statements to construct arrays with only the same types of values, we do not need to clearly define the types of arrays.shoppinglistCan also be written as follows:

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

Because the values in all literal statements are of the same type, Swift can inferString[]YesshoppinglistThe correct type of the variable in.

Access and modify Arrays

We can access and modify the array or subscript syntax through array methods and attributes. You can also use the read-only attribute of the array.countTo obtain 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 BooleanisEmptyAs a checkcountWhether the attribute value is 0.

If shoppingList. isEmpty {println ("The shopping list is empty. ")} else {println (" The shopping list is not empty. ")} // print" The shopping list is not empty. "(shoppinglist is not empty)

You can also useappendMethod to add a new data item after the array:

ShoppingList. append ("Flour") // shoppingList now has three data items, some of which are spread

In addition, the addition value assignment operator (+=You can also add data items directly after the array:

ShoppingList + = "Baking Powder" // The shoppingList contains four items.

We can also use the addition assignment operator (+=Directly add an array with the same data type.

ShoppingList + = ["Chocolate Spread", "Cheese", "Butter"] // shoppingList has 7 items

You can directly use the subscript syntax to obtain the data items in the array, and put the index value of the data items we need in square brackets of the array name:

Var firstItem = shoppingList [0] // The first item is "Eggs"

Note that the index value of the first item in the array is0Instead1. Array indexes in Swift always start from scratch.

We can also use subscript to change the data value corresponding to an existing index value:

ShoppingList [0] = "Six eggs" // The first item is "Six eggs" instead of "Eggs"

You can also use subscript to change a series of data values at a time, even if the number of new data is different from that of original data. In the following example"Chocolate Spread","Cheese", And"Butter"Replace"Bananas"And"Apples":

ShoppingList [4... 6] = ["Bananas", "Apples"] // shoppingList has six items

Note:

We cannot add new items at the end of the array using the subscript syntax. If we try to use this method to retrieve data out of the index or set a new value, we will cause a runtime error. We can use the index value and the array'scountAttribute comparison to check whether an index is valid. Except whencountWhen the value is equal to 0 (indicating that this is an empty array), the maximum index value is alwayscount - 1Because the array is zero index.

Call the Arrayinsert(atIndex:)To add data items before a specific index value:

ShoppingList. insert ("Maple Syrup", atIndex: 0) // shoppingList has seven items. // "Maple Syrup" is now the first item in this list.

This timeinsertCall a function to set the value"Maple Syrup"The initial position of the new data entry insertion list, and use0As the index value.

Similarly, we can useremoveAtIndexTo remove an item from the array. This method removes the data items stored in the array in a specific index value and returns the removed data item (we can ignore it when we don't need it ):

Let mapleSyrup = shoppingList. removeAtIndex (0) // data items whose index value is 0 are removed // shoppingList currently only has 6 items, besides, the value of the constant Maple Syrup // mapleSyrup is equal to the value of the removed data item"

After a data item is removed, the empty output items in the array are automatically filled. Therefore, the index value is0The value of the data item is equal"Six eggs":

FirstItem = shoppingList [0] // firstItem is now equal to "Six eggs"

If you only want to remove the last entry from the array, you can useremoveLastMethod insteadremoveAtIndexTo avoid getting the ArraycountAttribute. Like the latter, the former also returns the removed data items:

Let apples = shoppingList. removeLast () // the last item of the array has been removed. // shoppingList now has only five items, excluding the value of cheese // apples constant and is now equal to "Apples" String

Array Traversal

We can usefor-inLoop to traverse data items in all Arrays:

for item in shoppingList {    println(item)}// Six eggs// Milk// Flour// Baking Powder// Bananas

If we need the value and index value of each data item at the same time, we can use globalenumerateFunction to traverse the array.enumerateReturns a key-value pair group consisting of the index value and data value of each data item. We can extract this key-Value Pair component into a temporary constant or variable for traversal:

for (index, value) in enumerate(shoppingList) {    println("Item \(index + 1): \(value)")}// Item 1: Six eggs// Item 2: Milk// Item 3: Flour// Item 4: Baking Powder// Item 5: Bananas

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.