Swift provides two collection types to store collections, arrays, and dictionaries. An array is a collection of serialized lists of the same type. A dictionary is an unordered collection that can get a value using a unique identifier similar to a key.
In Swift, both the keys and values of an array and a dictionary must be clear about its type. This means that the array and the dictionary do not insert a value of the wrong type so that an error occurs. This also means that when you retrieve a value from an array and a dictionary, you can determine its type.
Swift uses a determined collection type to ensure that the code works without error, and that you can catch errors earlier in the development phase.
Note
Swift's array storage of different types shows different behaviors, such as variables, constants, or functions and methods. For more information see mutability of collections and assignment and Copy Behavior for Collection Types.
1, array
Arrays are serialized lists that store different values of the same type. The same value can appear multiple times in different places in the array.
The swift array is a store-determined value, and the Nsarray and Nsmutablearray classes in this objective-c are different. Because they are stored in a variety of objects and do not provide specific information to return any related objects. In Swift, whether it be a definite declaration or an implicit declaration, an array is very sure of what type it is stored in, and it does not necessarily require a class object to be stored. So the swift array is type-safe because it always determines the values it can contain.
Abbreviated syntax for arrays
The complete definition of an array is array<sometype>. Where SomeType is the type you want to include. You can also use a shorthand syntax like sometype[. Although the two methods are functionally identical. But we recommend the latter, and it will continue throughout the book.
Array Real amount (literals array)
You can initialize an array with an array literals, which is a shorthand for creating an array that contains one or more values. An array literals is the value that it contains, and the "," delimiter already includes the brackets of the above content for "[]":
Copy Code code as follows:
[Value 1, Value 2, value 3]
The following example creates an array called Shoppinglist, which stores the type of string (string).
Copy Code code as follows:
var shoppinglist:string[] = ["Eggs", "Milk"]
Initializes a shoppinglist using two initialization parameters
The shoppinglist variable is defined as an array of string types, writing string[]. Because this array is determined to be a string type, it can only store values of string type. In this case, the shoppinglist array is initialized with two string-type values ("Eggs" and "Milk") and Arrays of real (array literals).
Attention
The shoppinglist array is defined as a variable (using the var identifier) rather than a constant (using a let identifier), so you can add the element directly in the following example.
In this example, the array literals contains only two string-type values, which conform to the definition of the shoppinglist variable (which can only contain an array of string types), so the allocated array's real amount literals) is allowed to initialize with a value of two string types.
Thanks to Swift's type inference, you can not specify the type when you initialize it with the same type of value. Initialization shoppinglist can be replaced with the following method.
Copy Code code as follows:
var shoppinglist = ["Eggs", "Milk"]
Because all values in array literals are of the same type, swift can infer that the shoppinglist type is an array of strings (string[).
Reading and modifying arrays
You can read and modify arrays by methods and attributes, or by subscript.
Reads the length of the array by read-only property count;
Copy Code code as follows:
println ("The shopping list contains \ (shoppinglist.count) items.")
Prints "The shopping list contains 2 items."
Check the length of the array by a IsEmpty property that returns a Boolean type of 0
Copy Code code as follows:
If Shoppinglist.isempty {println ("The shopping list is empty.")
else {println ("The shopping list is not empty.")
}
Prints "The shopping list is not empty."
Adding an element at the end of an array can be done by append method
Copy Code code as follows:
Shoppinglist.append ("flour")
Shoppinglist now contains 3 elements
You can even add an element to the end of an array with the (+ =) operator
Copy Code code as follows:
Shoppinglist = "Baking powder"
Shoppinglist now contains 4 elements
You can also use the (+ =) operator to add an array to the end of another array
Copy Code code as follows:
Shoppinglist + = ["Chocolate spread", "Cheese", "Butter"]
Shoppinglist now contains 7 elements
To remove a value from an array, you can use the following banner method. If you know the index value of an element, you can get the element by filling in the index value in brackets after the array name.
Copy Code code as follows:
var FirstItem = shoppinglist[0]
FirstItem equals "Eggs"
Note that the index value of the first element of the array is 0, and an array that is not 1,swift is always indexed by 0;
You can use the following slogan to modify an existing value through an index.
Copy Code code as follows:
Shoppinglist[0] = "Six eggs"
The first value in the list is equal to "Six eggs" and not equal to "eggs"
You can use the following banner to change a series of values at once, although the modified range is much larger than the value you want to modify. In the following thunder, replace "chocolate spread", "Cheese", "Butter", "Bananas", "Apples":
Copy Code code as follows:
SHOPPINGLIST[4...6] = ["Bananas", "Apples"]
Shoppinglist now contains 6 elements
Note that you can't add an element to an array using the next tagline, and if you try to get or set an element using subscript syntax, you'll get a run-time error. However, you can use the Count property to verify that the index is correctly reused. When Count is 0 o'clock (meaning that the arrays are empty), Count-1 exceeds the valid range of the index because the index of the array always starts at 0.
Inserts a value at a specific index position, you can use the Insert (Atindex:) method
Copy Code code as follows:
Shoppinglist.insert ("Maple syrup", atindex:0)
Shoppinglist now contains 7 elements
"Maple syrup" in the first bit of the array
This calls the Insert method to indicate that a new element, "Maple syrup", is inserted in the position where the index of shoppinglist is 0.
Similarly, you can call the Removeatindex method to remove a specific element. This method removes the element from the specified index and returns the removed element (although you do not care about the return value).
Copy Code code as follows:
Let Maplesyrup = Shoppinglist.removeatindex (0)
The element with index position 0 is removed
Shoppinglist now contains 6 elements, excluding Maple syrup
The Maplesyrup constant equals the removed "Maple syrup" string
When the element is removed, the position of the array vacancy will be filled, so the element with an index position of 0 is once again equal to "Six eggs":
Copy Code code as follows:
FirstItem = shoppinglist[0]
FirstItem now equals "Six eggs."
If you remove the last element from the array, it is more convenient to use the Removelast method than the Removeatindex because the latter needs to compute the length of the array through the Count property. As with the Removeatindex method, Removelast returns the removed element.
Copy Code code as follows:
Let apples = shoppinglist.removelast ()
The last element of the element is removed
Shoppinglist now contains 5 elements, excluding cheese
The apples constant is now equal to the removed "apples" string
Traversing an array
You can use the for-in loop to traverse the values in an array
Copy Code code as follows:
For item in Shoppinglist {println (item)
}
Six eggs
Milk
Flour
Baking powder
Bananas
If you need an indexed value for the shaping of each element, it is more convenient to use the enumerate function instead, and the enumerate function returns a tuple (tuple) that contains the index and value of the element for each element. You can iterate through the partial decomposition of the progenitor and store it in a temporary variable or constant.
Copy Code code as follows:
For (index, value) in enumerate (shoppinglist) {println ("Item \ (index + 1): \ (value)")
}
Element 1:six Eggs
Element 2:milk
Element 3:flour
Element 4:baking Powder
Element 5:bananas
For more for-in circular information, see for Loops.
Creating and initializing arrays
creates an initialization syntax for the use of an empty array and a determined type that does not contain initialization values:
Copy Code code as follows:
var someints = int[] ()
println ("someints is of type int[] with \ (someints.count) items.")
Prints "someints is of type int[] with 0 items."
Note that the Someint variable is identified as int[] because it uses the initialization method of the build int[].
Alternatively, if the context already provides type information, such as function arguments or constants and variables of the type that have been identified, you can create an empty array from the empty array literals, writing [] (empty bracket pairs).
Copy Code code as follows:
Someints.append (3)
Someints now contains 1 int types of elements
Someints = []
Someints is now an empty array, but the type is still int[];
The SWIFT array type also provides an initialization method to create an array that determines the length and provides a default value. You can add a new array by this initialization method, the number of elements becomes count, and the appropriate default value is Repeatedvalue
Copy Code code as follows:
var threedoubles = double[] (count:3, repeatedvalue:0.0)
The type of Threedoubles is double[], and equal to [0.0, 0.0, 0.0]
Thanks to type inference, you do not need to specify the type of array storage to use this initialization method because it can be inferred from the default value.
Copy Code code as follows:
var anotherthreedoubles = Array (Count:3, repeatedvalue:2.5)
Anotherthreedoubles is inferred as double[], and equal to [2.5, 2.5, 2.5]
Finally, you can use the (+) operator to create a new array that adds two existing arrays
This new array type is inferred from the two arrays you added
Copy Code code as follows:
var sixdoubles = threedoubles + anotherthreedoubles
Sixdoubles are inferred as double[] and equal to [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
2. Dictionary
A dictionary is a container that stores the same type but different values. Each value corresponds to this unique key (key), as if each value in the dictionary has an identifier. The elements in an array are different, and there is no special sequence of elements in the dictionary. You can use a dictionary when you need to find a batch value based on an identifier. Similarly, a real object dictionary is often used as an identifier to find a particular dictionary.
Swift Dictionaries store a type of specific keys and values, and Objective-c nsdictionary and nsmutabledictionary by a certain difference because they are using various objects as their keys and values, And does not provide any specific information about the object. In Swift, for a particular dictionary, the keys and values that it can store are determined, either explicitly declared or implicitly inferred types.
Swift's Dictionary is written dictionary<keytype,valuetype>,keytype is the key you want to store, valuetype is the value you want to store.
The only limitation is that the KeyType must be hashed (hashable)--that is, to provide a form that allows them to identify themselves independently. All of Swift's underlying types (for example, String, shape (Int), double and Boolean (bool)) are hashes by default (Hashable), and these types are often used as dictionaries in the keys. Enumeration member values do not require assistance values (associated values) (described in enumerations) also because they are also hashed (hashable) by default.
Dictionary Real Amount (Dictionary literals)
You can initialize a dictionary directly with a dictionary of real quantities (Dictionary literals). The same syntax as the previous definition of an array literals. The dictionary real amount (Dictionary literals) is the use of shorthand to write one or more key-value pairs to define a dictionary.
A key-value pair is a combination of a key and a value. In the dictionary real amount (Dictionary literals), each key-value pair always splits the key and value with a colon. A key-value pair is written as a list, separated by commas, and enclosed by a pair of brackets []:
Copy Code code as follows:
[Key 1:value 1, key 2:value 2, key 3:value 3]
In the following example, a dictionary will be created to store the name of the international airport. In this dictionary, the key is the three-word International Air Transport Association code, and its value is the name of the airport:
Copy Code code as follows:
var airport:D ictionary<string, string> = ["Tyo": "Tokyo", "DUB": "Dublin"]
The airport dictionary is defined as a type dictionary<string, String>, which means that the key type of the dictionary is string, and the type of its value is also string.
Attention
An airport dictionary is defined as a variable (using the var identifier) rather than a constant (using a let identifier), so you can add the element directly in the following example.
The airport dictionary is initialized with a dictionary real amount (Dictionary literals) that contains two key-value pairs. The first pair consists of a key called "Tyo" and a value called "Tokyo", and the second pair has a key called "DUB" and a value called "Dublin".
This dictionary literal (Dictionary literals) contains two strings (string): a pair of strings. This conforms to the type of the airport variable definition (a dictionary consists only of string keys and string values), so it is allowed to be two initialization elements of an airport dictionary when allocating a dictionary literal (Dictionary literals).
and arrays, if you use the same type when initializing a dictionary, you can not indicate the type of dictionary.
Airport initialization can be replaced by the following shorthand:
Copy Code code as follows:
var airports = ["Tyo": "Tokyo", "DUB": "Dublin"]
Since all the keys are literally the same type, all values are the same type, so swift can be inferred as dictionary<string, string> is the correct type of the airports dictionary.
Reading and modifying dictionaries
You can read and modify dictionaries by attributes, methods, or subscripts. As with arrays, you use the read-only Count property to examine how many elements the dictionary (Dictionary) contains.
Copy Code code as follows:
println ("The Dictionary of Airports contains \ (airports.count) items.")
Prints "The Dictionary of Airports contains 2 items."
You can add an element to a dictionary by using the slogan. Use the appropriate type as the new key and assign it a suitable value
Copy Code code as follows:
airports["LHR"] = "London"
Airports Dictionary now has 3 items
You can also use the slogan to change the value associated with a particular key.
Copy Code code as follows:
airports["LHR"] = "London Heathrow"
The value of "LHR" has been changed to "London Heathrow"
Similarly, use a dictionary of Updatevalue (forkey:) method to set or update the value of a particular key. As with the subscript example above, Updatevalue (Forkey:) method sets its value if the key does not exist, and it updates its value if the key exists, unlike the subscript, Updatevalue (forkey:) method if it is updated, it returns the original old value Rthis enables you can use this to determine if an update has occurred.
Copy Code code as follows:
Updatevalue (Forkey:) method returns an optional value of the same type as the value of a dictionary. For example, if a string is the type of the value of the dictionary, then string is returned? or "optional String," which contains an old value that is updated if the value is nil and a value that does not exist.
If Let OldValue = Airports.updatevalue ("Dublin International", Forkey: "DUB") {
println ("The old value of DUB was \ oldValue)."
}
Prints "The old value for DUB is Dublin."
You can also use the following banner to read a value through a specific key. Because if his value does not exist, he can return his key, and the dictionary's next tagline returns an optional value of the type of the dictionary's value. If the key in the dictionary contains the corresponding value, the dictionary will return the value of the key, or return nil
Copy Code code as follows:
If let Airportname = airports["DUB"] {
println ("The name of the airport is \ (airportname).")
} else {
println ("That airport isn't in the airports dictionary.")
}
Prints "The name of the airport is Dublin International."
You can use the next banner to assign his value to nil to remove the key-value pair.
Copy Code code as follows:
airports["APL"] = "Apple International"
"Apple International" is not APL's real airport, so delete it
airports["APL"] = Nil
APL has been removed from the dictionary
Similarly, removing a key-value pair from a dictionary can be done using the Removevalueforkey method, which, if there is a value for the key, removes a key-value pair and returns the removed value, otherwise returns nil.
Copy Code code as follows:
If Let Removedvalue = Airports.removevalueforkey ("DUB") {
println ("The removed airport ' s name is \ (removedvalue).")
} else {
println ("The Airports Dictionary does not contain a value for DUB.")
}
Prints "The removed airport ' s name is Dublin International."
Traverse Dictionary
You can use a for-in loop to traverse the dictionary's key-value pairs. Each element of the dictionary returns a tuple, which you can decompose in a circular section and store it with a temporary variable or constant.
Copy Code code as follows:
For (Airportcode, Airportname) in airports {
println ("\ (Airportcode): \ (airportname)")
}
Tyo:tokyo
Lhr:london Heathrow
For more information about the for-in loop, see for Loops.
You can also read the dictionary keys or values attribute to traverse the dictionary's key or value collection.
Copy Code code as follows:
For Airportcode in Airports.keys {
println ("Airport code: \ (Airportcode)")
}
Airport Code:tyo
Airport CODE:LHR
For Airportname in Airports.values {
println ("Airport name: \ (airportname)")
}
Airport Name:tokyo
Airport Name:london Heathrow
If you need an interface to create an array of keys or values for a dictionary, you can use the keys or values properties to initialize a value.
Copy Code code as follows:
Let Airportcodes = Array (Airports.keys)
Airportcodes is ["Tyo", "LHR"]
Let Airportnames = Array (airports.values)
Airportnames is ["Tokyo", "London Heathrow"]
Attention
The dictionary type in Swift is a serializable collection, and if you need to serialize the fetch key, the value, or the key value pair, traversing the dictionary is not specifically described.
Create an empty Dictionary
As with dictionaries, you can create an empty dictionary using the syntax of a certain type.
Copy Code code as follows:
var namesofintegers = Dictionary<int, string> ()
Namesofintegers is an empty dictionary<int, string> type of dictionary
This example creates a int,string type dictionary to store an integer value that is more readable. Its keys are of type int, and their values are string types.
If the type information is already provided in the context, you can create an empty dictionary using a dictionary (Dictionary Literal), writing [;] (Contains a colon by a pair []:)
Copy Code code as follows:
NAMESOFINTEGERS[16] = "Sixteen"
Namesofintegers now contains 1 key-value pairs
Namesofintegers = [:]
Namesofintegers is an empty dictionary of type int and string.
Attention
In this scenario, the swift array and dictionary type is a built-in collection. More built-in types and collections see generics
3. Variable collection type
Both arrays and dictionaries store different variables together in a set. If you create an array or a dictionary, and then contain a variable, this variable is called a mutable (mutable), which means that you can add more elements to change the length of the collection after creation, or remove the already included. Conversely, if you define an array or dictionary as a constant, the array or dictionary is not mutable, and their length cannot be changed.
In the dictionary, immutable also means that you cannot replace the value of a key that already exists. A immutable dictionary, once set, cannot be changed.
The invariant of an array is a little bit different. However, you still can't do anything that might modify the immutable group behavior. But you can reset an already existing index, which allows you to better optimize the performance of the array when the length of Swift's array is determined.
Arrays that have variable behavior also affect the allocation and modification of an array instance, and see Assignment and Copy Behavior for Collection Types.
Attention
In all cases, this is a good practice to create immutable sets when the length of an array does not need to be changed.
I'm sure the swift compiler can optimize the set you created.