About Swift set types and swift Sets

Source: Internet
Author: User
Tags hashable

About Swift set types and swift Sets

Swift sets are represented by arrays and dictionaries. It perfectly stores everything you want to store.

An array is a set of serialized lists of the same type. It is used to store different values of the same type. A dictionary is also an array, but its storage method is similar to Map. It binds values with one click. It is a set of non-serialized sets.

In Swift, the keys and values of arrays and dictionaries must specify their types.

This means that the array and dictionary do not insert an incorrect type value, so that an error occurs. This also means that you can determine its type when retrieving values in arrays and dictionaries.


Swift uses a definite set type to ensure that the code works without errors, and allows you to capture errors earlier in the development stage.

1, Array
An array is a serialized list that stores different values of the same type. The same value can appear multiple times in different positions of the array.

Swift arrays store determined values. The NSArray and NSMutableArray classes in Objective-C are different. Because they store various objects and do not provide any specific information about objects. In Swift, whether it is a definite declaration or an implicit declaration, an array is very certain about the type it stores, and it does not necessarily need to store class objects. Therefore, Swift arrays are type-safe, because they always determine the values they can contain.

Array syntax
The complete syntax for defining arrays is Array <SomeType>. SomeType is the type you want to include. You can also use a simple syntax similar to SomeType. Although these two methods are functionally the same. But we recommend the latter, and it will continue throughout this book.

Array real amount (Array Literals)
You can use an Array (Array Literals) to initialize an Array. It creates an Array containing one or more values in a simple way. An Array Literals is composed of the values it contains. The separator "," already includes the brackets in the preceding content:

The following example creates an array named shoppinglist to store strings.

The shoppinglist variable is defined as an array of the String type, written as String []. This array is determined to be of the String type, so it can only store values of the String type. Here, the shoppingList Array is initialized by writing two string types of values ("Eggs" and "Milk") and Array real amount (Array Literals.

Note:
The shoppingList array is defined as a variable (using var identifiers) rather than a constant (using let identifiers). Therefore, you can add elements directly in the following example.

In this example, the Array real amount (Array Literals) only contains two String types of values, which conforms to the shoppingList variable definition (can only contain String type arrays ), therefore, Array Literals can be initialized with two string values.

Thanks to the Swift type inference, you can leave the type unspecified when initializing with the same type value. The following method can be used to initialize shoppingList.

Because all values in Array Literals are of the same type, Swift can infer that the shoppingList type is a String Array (String []).

Read and modify Arrays
You can read and modify arrays by using methods, attributes, or subscript.

Read the length of the array using the read-only attribute count;

Check whether the array length is 0 by returning a Boolean isEmpty attribute

Add an element to the end of the array by using the append method.

You can even use the (+ =) operator to add an element to the end of the array.

You can also use the (+ =) operator to add an array to the end of another array.

You can use the subscript syntax to retrieve a value from the array. If you know the index value of an element, you can enter the index value in the brackets after the array name to obtain this element.

Note:

The index value of the first element of the array is 0, not 1. The Swift array always indexes 0;

You can use the subscript syntax to modify an existing value through the index.

You can use the subscript syntax to change a series of values at a time, although the modified region is much larger than the value to be modified. Replace "Chocolate Spread", "Cheese", "Butter", "Bananas", and "Apples" in the following Lei Zi ":

Note: you cannot use subscript syntax to add an element to an array. If you try to use subscript syntax to obtain or set an element, you will get a runtime error. However, you can use the count attribute to verify that the index is correct before using it. When count is 0 (meaning the array is empty), count-1 is out of the valid range of the index, because the index of the array always starts from 0.

Insert a value at a specific index location. You can use the insert (atIndex :) method.

Here, the insert method is called to indicate that a new element "Maple Syrup" is inserted at the position where the index of shoppingList is 0"

Similarly, you can call the removeAtIndex method to remove specific elements. This method removes the element at the specified index and returns the removed element (although you do not care about the returned value ).

When an element is removed, the position of the array vacancy will be filled, so now the element whose index position is 0 is equal to "Six eggs" again ":

If you remove the last element from the array, the removeLast method is more convenient than removeAtIndex, because the latter needs to calculate the length of the array through the count attribute. Like the removeAtIndex method, removeLast returns the removed element.

Traverse Arrays
You can use the for-in loop to traverse the values in the array.

If you want to replace the integer index value of each element, it is more convenient to use the enumerate function. The enumerate function returns a tuple containing the index and value of each element ). You can break down the ancestor in the traversal part and store it in temporary variables or constants.

 

Create and initialize Arrays
The initialization syntax used to create an empty array and determine the type (excluding the initialization value:

Note:

The someInt variable is determined to be Int [] because it uses the initialization method that generates Int.

Alternatively, if the context already provides type information, such as function parameters or constants and variables of the determined type, you can create an empty Array from an empty Array (Array Literals, write [] (empty braces ).

The Swift array type also provides initialization methods to create arrays that determine the length and provide default values. You can use this initialization method to add a new array. The number of elements becomes count. The appropriate default value is repeatedValue.

Thanks to type inference, you can use this initialization method without specifying the type stored in this array, because it can be inferred from the default value.

Finally, you can use the (+) operator to create a new array and add two existing arrays.
This new array type is inferred from the two arrays you added.

2, Dictionary

Dictionaries store the same type, but different values are easy. Each value corresponds to this unique Key, just as each value in the dictionary has an identifier. The elements in the Data Group are different from each other. The elements in the dictionary do not have special sequences. You can use a dictionary to find values in batches Based on identifiers. Same, true
The item dictionary is often used as an identifier to find a specific dictionary.

The Swift dictionary stores a specific type of key and value, which is different from the NSDictionary and NSMutableDictionary of Objective-C because they use various objects as their key and value, and does not provide any specific information about the object. In Swift, keys and values stored in a specific dictionary are fixed, whether explicitly declared or implicitly inferred.

The Swift Dictionary is written as Dictionary <KeyType, ValueType>, KeyType is the key you want to store, And ValueType is the value you want to store.

The only restriction is that the KeyType must be hashable, which provides a form for independent identification. All basic types of Swift (such as String, Int, Double, and Boolean) are hashable by default ), and these types are often used as Dictionary keys. The associated values (which are described in Enumerations) are not required for enumeration member values because they are also hashable by default ).

Dictionary quantity (Dictionary Literals)
You can use a Dictionary to initialize a Dictionary. The syntax is the same as that defined in Array Literals. Dictionary Literals is to use a simple method to directly write one or more key-value pairs to define a Dictionary.

A key-value pair is a combination of keys and values. In Dictionary Literals, each key-Value Pair always uses a colon to separate keys and values. The key-value pair is written as a list separated by commas (,) and is enclosed by a pair of brackets:

In the following example, a dictionary is created to store the name of an international airport. In this dictionary, the key is a three-character International Air Transport Association code, and its value is the name of the airport:

The airport Dictionary is defined as a Dictionary <String, String> type, which means that the Dictionary's key type is String, and its value type is also String.

Note:
The airport dictionary is defined as a variable (using var identifiers) rather than a constant (using let identifiers). Therefore, you can add elements directly in the following example.

The airport Dictionary is initialized using a Dictionary Literals that contains two key-value pairs. The first pair is composed of a key named "TYO" and a value named "Tokyo". The second pair has a key named "DUB" and a value named "Dublin.

Dictionary Literals contains two strings: String pairs. This is consistent with the type defined by the airport variable (a Dictionary only includes the String key and String value), so when assigning the Dictionary actually (Dictionary Literals) can be used as two initialization elements of the airport dictionary.

Like arrays, if you use the same type when initializing a dictionary, you do not specify the dictionary type.
Airport initialization can be replaced by the following simple statement:

Because all keys are of the same type literally and all values are of the same type, Swift can infer that the Dictionary <String, String> is the correct type of the airports Dictionary.

Read and modify dictionaries
You can use attributes, methods, or subscripts to read and modify dictionaries. Like an array, you use the read-only count attribute to check the number of elements contained in a Dictionary.

You can use the subscript syntax to add an element to a dictionary. Use the appropriate type as the new key and assign it a proper value

You can also use the subscript syntax to change the values associated with a specific key.

Similarly, use the updateValue (forKey :) method of the dictionary to set or update the value of a specific key. like the subscript example above, the updateValue (forKey :) method sets its value if the key does not exist. If the key exists, it updates its value, which is different from the subscript, if the updateValue (forKey :) method is updated, the old value rThis enables you can use to determine whether an update has occurred.

You can also use the subscript syntax to read a value through a specific key. If the value does not exist, its key can be returned. The dictionary's syntax returns an optional value of the dictionary value type. If the key in the dictionary contains the corresponding value, the syntax of the dictionary will return the value corresponding to the key; otherwise, nil will be returned.

You can use the subscript syntax to assign the value to nil to remove this key-value pair.

// APL has been removed from the dictionary
Similarly, you can use the removeValueForKey method to remove a key-value pair from a dictionary. If a key-Value Pair exists in this method, it is removed and the removed value is returned, otherwise, nil is returned.

Traverse dictionary
You can use a for-in loop to traverse dictionary key-value pairs. Every element in the dictionary returns a tuple. You can break down this ancestor in the loop part and store it with temporary variables or constants.

You can also read the dictionary's keys attribute or values attribute to traverse the dictionary's key or value set.

If you need an interface to create an array of dictionary keys or values, you can use the keys or values attribute to initialize a value.

Note:
The dictionary type in Swift is a non-serialized set. If you need to serialize and retrieve keys, values, or key-value pairs, the traversal dictionary is not described in detail.

Create an empty dictionary
Like a dictionary, you can create an empty dictionary by using the "OK" syntax.

In this example, an Int and String dictionary is created to store the integer with better readability. Its keys are of the Int type and their values are of the String type.
If the context already provides type information, you can use a Dictionary (Dictionary Literal) to create an empty Dictionary and write [;] (a pair of [] contains a colon :)

Note:
In this scenario, the Swift array and dictionary types are a built-in set.

3, Variable set type

Arrays and dictionaries store different variables together in a collection. if you create an array or dictionary that contains a variable, the variable created is called mutable, you can add more elements to change the length of the set, or remove included elements. On the contrary, if you define an array or dictionary as a constant, the array or dictionary is not variable and their length cannot be changed.
In the dictionary, immutable means that you cannot replace the existing key value. An unchangeable dictionary cannot be changed once set.
The immutable array is slightly different. However, you still cannot perform any behavior that may modify the immutable array. However, you can reset an existing index to optimize the array performance when the length of the Swift array is determined.
Arrays with variable behavior also affect the allocation and modification of array instances.
Note:
In all examples, this is a good exercise to create an immutable set, when the length of the array does not need to be changed.
I'm sure the Swift compiler can optimize the set you created.

 

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.