iOS development language Swift Getting started serial---collection types

Source: Internet
Author: User

iOS development language Swift Getting Started serial-collection type

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. Although the dictionary stores the same type of data values in disorder, it needs to be referenced and addressed by a unique identifier (that is, a key-value pair).
The types of data values stored in arrays and dictionaries in the swift language must be unambiguous. This means that we cannot insert an incorrect data type into it. It also shows that we can be very confident about the type of value we get. Swift's use of explicit type collections ensures that our code is very clear about the types of work required, and that we can find any type mismatch errors early in development.
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 more information, see the section on the behavior of collections in assignment and replication.
  

Array

Arrays store multiple values of the same type using an ordered list. The same value can appear multiple times in different locations of an array.
The swift array is specific to the type of elements it stores. Unlike Objective-c's Nsarray and Nsmutablearray, these two classes can store objects of any type and do not provide any special information about the returned object. In Swift, a data value must be explicitly typed before it is stored in an array, by means of an explicit type callout or type inference, and not by a class type. For example, if we create an array of int value types, we cannot insert any data that is not of type int. Arrays in Swift are type-safe, and the types they contain must be explicit.
  simple syntax for arrays
The write Swift array should follow a form like array, where SomeType is the only data type allowed in this array. We can also use simple syntax like sometype[]. Although the two forms are functionally identical, they are recommended for a shorter type, and are used in this form to use arrays.
  Array Construct statement
We can use the literal to construct the array, which is a simple way to construct an array with one or more numeric values. A literal is a series of values separated by commas and enclosed by square brackets. [Value 1, Value 2, value 3].
The following example creates an array called Shoppinglist and stores the string:

varString[] = ["Eggs""Milk"]// shoppingList 已经被构造并且拥有两个初始项。

The shoppinglist variable is declared as "an array of string value types", as string[]. Because this array is specified to have only a data structure of string, only the string type can be accessed in it.  Here, the shoppinglist array is constructed from two string values ("Eggs" and "Milk") and is defined by the literal.  Note: The shoppinglist array is declared as a variable (var keyword creation) instead of a constant (let is created) because more data items may be inserted in the future. In this example, the literal contains only two string values.  Matches the variable declaration of the array (only the array of strings), so this literal allocation process allows the shoppinglist to be constructed with two initial entries. Because of the Swift type inference mechanism, we do not have to define the type of the array clearly when we construct only the same type value array with literal constructs. The structure of the shoppinglist can also be written like this:

var shoppingList = ["Eggs""Milk"]

Because the values in all literals are the same type, Swift can infer that string[] is the correct type of variable in the shoppinglist. Accessing and modifying arrays we can access and modify arrays by using the methods and properties of the array, or under 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.")// 输出"The shopping list contains 2 items."(这个数组有2个项)

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

if shoppingList.isEmpty {    println("The shopping list is empty."else {    println("The shopping list is not empty.")}// 打印 "The shopping list is not empty."(shoppinglist不是空的)

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

shoppingList.append("Flour")// shoppingList 现在有3个数据项,有人在摊煎饼

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

"Baking Powder"// shoppingList 现在有四项了

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

shoppingList += ["Chocolate Spread""Cheese""Butter"]// shoppingList 现在有7项了

You can use the subscript syntax directly to get the data items in the array, placing the index values of the data items we need in the brackets directly in the array name:

var firstItem = shoppingList[0]// 第一项是 "Eggs"

Note that the first item in the array has an index value of 0 instead of 1.  The array index in Swift always starts from zero. We can also use subscripts to change the data values for an existing indexed value:

shoppingList[0"Six eggs""Six eggs""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 example replaces "Chocolate Spread", "Cheese", and "Butter" with "Bananas" and "Apples":

shoppingList[4...6] = ["Bananas""Apples"]// shoppingList 现在有六项

Note: We cannot add new items at the end of the array by using the following banner. If we try to retrieve data from an index that is out of bounds or set new values in this way, we will throw a run-time error. We can use the index value and the Count property of the array to compare to verify the validity of an index before using it.  Except when Count equals 0 o'clock (which means that this is an empty array), the maximum index value is always count-1 because the array is 0 indexed. Call the Insert (Atindex method of the array to add the data item before a specific index value:

shoppingList.insert("Maple Syrup"0)// shoppingList 现在有7项// "Maple Syrup" 现在是这个列表中的第一项

This time the Insert function calls the new data item with a value of "Maple syrup" to the beginning 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)// 索引值为0的数据项被移除// shoppingList 现在只有6项,而且不包括Maple Syrup// mapleSyrup常量的值等于被移除数据项的值 "Maple Syrup"

When the data item is removed, the empty items in the array are filled in automatically, so now the value of the data item with index value 0 is again equal to "Six eggs":

firstItem = shoppingList[0"Six eggs"

If 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()// 数组的最后一项被移除了// shoppingList现在只有5项,不包括cheese// apples 常量的值现在等于"Apples" 字符串

Traversal of an array we can use the for-in loop to iterate through the data items in all the arrays: if we need both the value of each data item and the index value, we can use the global enumerate function for array traversal. Enumerate returns a tuple that consists of index values and data values for each data item. We can break this tuple into temporary constants or variables to traverse:

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

For more information about for-in loops, see for loops.  Create and construct an array we can use construct syntax to create an empty array of specific data types: Note that someints is set to the output of a int[] constructor, so its variable type is defined as int[]. In addition, if the type information is provided in the code context, such as a function parameter or a constant or variable of a defined type, we can use an empty array statement to create an empty array, which is simple: [] (a pair of empty square brackets):

someInts.append(3)// someInts 现在包含一个INT值someInts = []// someInts 现在是空数组,但是仍然是Int[]类型的。

The array type in Swift also provides a construction method that can create a specific size and that all data is default. We can pass in the array constructor the number of data items (count) and the appropriate type of initial values (Repeatedvalue) that are ready to be added to the new array:

var3, repeatedValue:0.0)// threeDoubles 是一种 Double[]数组, 等于 [0.0, 0.0, 0.0]

Because of the existence of type inference, we do not need to specifically specify the data types stored in the array when we use this construction method, because types can be inferred from the default values:

isasandequals [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 inferred from the data type of the two arrays:

var sixDoubles = threeDoubles + anotherThreeDoubles// sixDoubles 被推断为 Double[], 等于 [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
Dictionary

A dictionary is a container that stores multiple values of the same type. Each of the values (value) is associated with a unique key (key), which is the identifier of the value data in the dictionary. The data items in the dictionary are not in a specific order, unlike the data items in the array.  We use dictionaries when we need to access data through identifiers (keys), which is largely the same way that we use dictionaries in the real world to find meanings. The use of Swift's dictionaries requires specifying that keys and value types can be stored. Unlike Objective-c, Nsdictionary and Nsmutabledictionary classes can use any type of object for keys and values and do not provide any essential information about these objects.  In Swift, keys and values that can be stored in a particular dictionary must be clearly defined in advance, by means of explicit type labeling or type inference. Swift's Dictionary uses dictionary

112233]

The following example creates a dictionary that stores the name of the international airport. In this dictionary the key is a three-letter international air Transport related Code, the value is the airport name:

var airports: Dictionary<StringString> = ["TYO""Tokyo""DUB""Dublin"]

The airports dictionary is defined as a dictionary which means that the dictionary's keys and values are of type string.  Note: The airports dictionary is declared as a variable (with the var keyword) instead of a constant (let keyword) because more airport information is later added to the sample dictionary. The airports dictionary is initialized with a dictionary literal and contains two key-value pairs. The first pair of keys is tyo, and the value is Tokyo.  The second pair of keys is dub, and the value is Dublin. This dictionary statement contains two key-value pairs of type string:string.  They correspond to the type of the airports variable declaration (a dictionary with only string keys and string values) so this dictionary literal is the airport dictionary that constructs two initial data items. and arrays, if we use literal constructs to construct a dictionary, we don't have to define the type clearly. Airports can also be briefly defined in this way:

var airports = ["TYO""Tokyo""DUB""Dublin"]

Because all the keys and values in this statement are the same data type, Swift can infer that dictionary is the correct type for the airports dictionary. Reading and modifying dictionaries we can read and modify the dictionary using the dictionary's methods and properties, or use the next banner method. As with arrays, we can get the number of data items for a dictionary through the read-only property Count of the dictionary:

println("The dictionary of airports contains \(airports.count) items.")// 打印 "The dictionary of airports contains 2 items."(这个字典有两个数据项)

We can also use the subscript syntax in the dictionary to add new data items. You can use an appropriate type of key as the subscript index and assign a new value of the appropriate type:

airports["LHR""London"// airports 字典现在有三个数据项

We can also use subscript syntax to change the value of a particular key:

airports["LHR""London Heathrow""LHR""London Heathrow

As another subscript method, the dictionary's Updatevalue (Forkey method can set or update the value corresponding to a particular key. As shown in the example above, the Updatevalue (Forkey method sets the value when there is no corresponding value for the key or updates the existing value when it exists). Unlike the subscript method above, this method returns the original value before the updated value.  This makes it easy for us to check whether the update was successful. Updatevalue (The Forkey function returns an optional value that contains a dictionary value type.) For example: For a dictionary that stores string values, the function returns a string? Or a value of type "optional String". If the value exists, the optional value is equal to the value being replaced, otherwise it will be nil.

iflet oldValue = airports.updateValue("Dublin Internation"for"DUB") {    println("The old value for DUB was \(oldValue).""The old value for DUB was Dublin."(DUB原值是dublin)

We can also use the subscript syntax to retrieve the values for a particular key in the dictionary. Because it is possible to use a key that has no value, the optional type returns the associated value of the key, otherwise it returns nil:

let airportName = airports["DUB"] {    ofis \(airportName).")} else {    isnotinofis Dublin Internation."(机场的名字是都柏林国际)

We can also use subscript syntax to remove a key-value pair from the dictionary by assigning a value of nil to the corresponding value of a key:

airports["APL""Apple Internation"// "Apple Internation"不是真的 APL机场, 删除它airports["APL"nil// APL现在被移除了

In addition, the Removevalueforkey method can be used to remove key-value pairs from the dictionary. This method removes the key-value pair when the key-value pair exists and returns the removed value or nil if there is no value:

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."
Dictionary traversal

We can use the for-in loop to iterate through the key-value pairs in a dictionary. The data items in each dictionary are returned by the (key, value) tuple, and we can use temporary constants or variables to decompose these tuples:

forin airports {    println("\(airportCode): \(airportName)")}// TYO: Tokyo// LHR: London Heathrow

For-in loops See for loops. We can also retrieve the key or value of a dictionary by accessing its keys or the Values property (which are all traversal collections):

forin airports.keys {    println("Airport code: \(airportCode)")}// Airport code: TYO// Airport code: LHRforin airports.values {    println("Airport name: \(airportName)")}// Airport name: Tokyo// Airport name: London Heathrow

If we just need to use a dictionary key collection or a value collection as a parameter to accept the array instance API, you can directly construct a new array using the keys or the Values property directly:

Arrayis ["TYO""LHR"Arrayis ["Tokyo""London Heathrow"]

Attention:
The dictionary type of Swift is an unordered collection type. where dictionary keys, values, key-value pairs are rearranged at the time of traversal, and the order is not fixed.
Create an empty Dictionary
We can create an empty dictionary using construction syntax like an array:

varString>()// namesOfIntegers 是一个空的 Dictionary<Int, String>

This example creates an int, an empty dictionary of type String, to store the names of integers in English.  Its key is type int, and the value is string type. If the context already provides the information type, we can use an empty dictionary literal to create an empty dictionary, which is recorded as [:] (a colon in brackets):

namesOfIntegers[16"sixteen"// namesOfIntegers 现在包含一个键值对namesOfIntegers = [:]// namesOfIntegers 又成为了一个 Int, String类型的空字典

Attention:
In the background, Swift's arrays and dictionaries are implemented by generic collections, and for more information about generics and collections, see Generics.
  

The variability of the collection

Both arrays and dictionaries store mutable values in a single collection. If we create an array or a dictionary and assign it to a variable, the set will be mutable. This means that we can change the size of this collection by adding more or removing existing data items after creation. Conversely, if we assign an array or dictionary to a constant, it is immutable and its size cannot be changed.
For dictionaries, immutability also means that we cannot replace the values of any of the existing keys. The contents of the immutable dictionary cannot be changed after being set for the first time. There is a difference in immutability arrays, but of course we can't try to change the size of any immutable array, but we can reset the values relative to the existing index. This allows the Swift array to still do great when the size is fixed.
The variable behavior of an array affects how an array instance is assigned and modified, and for more information, see the behavior of the collection in assignment and replication.
Attention:
It's good practice to create immutable groups when we don't need to change the size of the array. So Swift compilers can optimize the collections we create.

iOS development Language Swift entry---collection type

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.