Swift Learning-05--Collection type

Source: Internet
Author: User

Collection type

Swift provides Arrays, sets and dictionaries three basic collection types used to store data, arrays (Arrays) are sets of ordered data, collections (sets) are unordered sets of no duplicates, and dictionaries (dictionaries) are unordered key values Set of pairs

The types of data values stored in Arrays, sets, and dictionaries in the swift language must be clear, which means that we cannot insert incorrect data types into them, and colleagues this also shows that we can retrieve the type of the value very confidently

The variability of the collection

If you create a Arrays, sets and dictionaries and assign it to a variable. This collection will be mutable. This means that we can add more or remove existing data after creation, or change the data item in the collection, if we put the Arrays, set s and dictionaries are assigned constants, then he is immutable, his size and content cannot be changed.

It's good practice to create immutable collections when we don't need to change the collection, and Swift's editor can optimize the collections we create

Array

Arrays store multiple values of the same type using an ordered list, and the same values can appear multiple times in an unused position in an array

Note: The Array type of swift is bridged to the Nsarray class in the Foundation

Simple syntax for arrays

The write Swift array should follow a form like array<element>, where Element is the type of data that the position in this array allows to exist. We can also use simple syntax like [Element], although the two forms are functionally identical, but recommend a shorter one, and this form is used in this article to use the array

Create an empty array

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

var someints = [Int] ()

Print ("Someints is of type [int.] with \ (someints.count) items")

Note: By the type of the constructor, the value type of someints is inferred as [Int]

Alternatively, if the type information is already 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: [] (a pair of empty square brackets):

Someints.append (3)

Someints = []

Create an array with a default value

The Array type in Swift also provides a constructor that can create a specific size and all of the data is constructed by default, and we can add the number of data items (count) and the appropriate type of initial value (repeating) that are ready to be added to the new array:

var threedoubles = Array (repeating:0.0, Count:3)

Create an array by adding two arrays

We can use the addition operator (+) to combine two existing arrays of the same type, and the data type of the new array will be inferred from the data type of the two arrays.

var antherthreedoubles = Array (repeating:2.0, Count:3)

var sixdoubles = Array (repeating:3.0, Count:3)

var sevendoubles = antherthreedoubles + sixdoubles

Constructing an array with array literals

We can use the array literal to construct the array, which is a simple method of using one or more numeric values and constructing an array, and the array literal is a series of values separated by commas and enclosed in square brackets.

var shoppinglist: [String] = ["Eggs", "Mlik"]

The shoppinglist variable is declared as "an array of string value types", which is recorded as [string] because the array is specified to have only a data structure of string, so only the string type can be accessed in it.

In this example, the literal contains only two string values, matches the variable declaration of the array (only the array of strings), so the literal allocation process can be used as a way to construct the shoppinglist as a two-initial item

Because of Swift's inference mechanism, we do not have to clear the type definition of an array when we use literal constructs to have values of the same type.

Accessing and modifying arrays

We can access and modify the array through the methods and properties of the array, or use the following banner method

You can use the array's read-only property count to get the number of data items in the array

Print ("The shopping list contains \ (shoppinglist.count) items")

Use the Boolean property IsEmpty as an abbreviated form to check if the Count property is 0:

If shoppinglist.isempty{

Print ("There is a empty array")

}else{

Print ("There is a true array")

}

You can also use Append (_:) Method adds a new data item after the array

Shoppinglist.append ("flour")

In addition, you can add one or more data items with the same type directly after the array using the addition assignment operator (+ =)

Shoppinglist + = ["baking powder"]

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 square brackets after the array name

var fiesritem = shoppinglist[0]

Call the array's insert (_at:) method to add a data item before a specific index value

Shoppinglist.insert ("Hello", at:0)

If we only want to remove the last item in the array, you can use the Removelast () method instead of remove (_at:).

Traversal of an array

We can use the for-in loop to iterate through all the data items in the array.

For item in Shoppinglist {

Print (item)

}

If our colleagues need values and index values for each data item, we can use the enumerated () method to traverse, and enumerated () returns a tuple of each data item and data index value, so we can break the tuple into constants and variables to traverse.

for (Index,value) in shoppinglist.enumerated () {

Print ("Item \ (value) index:\ (index)")

}

Collection (sets)

Sets are used to store values of the same type and do not have a definite order, when the collection element order is unimportant or if you want each element to appear only once, you can use the collection instead of the array

Note: The swift type is bridged to the Nsset class in the foundation

Dictionary

A dictionary is a container that stores multiple values of the same type, with each value (value) associated with a unique key (key), the key as the identifier for the value data in the dictionary, and the data items in the array, and the data items in the dictionary are not in a specific order, and we use the dictionary when we need to access the data through identifiers.

Dictionary type Simplification syntax

Swift's Dictionary uses the dictionary<key,value> definition, which is the data type of the key in the dictionary, and value is the data type that corresponds to the keys stored in the dictionary.

Note: We can also use the simplified form of [key:value] to create a dictionary type, although both forms are functionally identical, but the latter is the preferred

Create an empty Dictionary

var namesofintegers = [int:string] ()

If the context already provides type information, we can use an empty dictionary literal to create an empty dictionary [:] (a colon in brackets)

NAMESOFINTEGERS[16] = "Sixteen"

Namesofintegers = [:]

Create a dictionary with dictionary literals

We can use a dictionary literal to construct a dictionary, which is similar to a set of literal constructs, a dictionary literal is a quick way to set one or more key-value pairs of writing Dictionary

var airports: [String:string] = ["YYZ": "Toronto Pearson", "DUG": "Dublin"]

As with arrays, when we construct a dictionary with a dictionary literal, if his keys and values have their own consistent type, then it's long not to write the type of the dictionary

For example var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

Accessing and modifying dictionaries

We can access and modify the dictionary through the methods and properties of the dictionary, or by using the following banner method

Gets the number of data items for a dictionary by using the dictionary's read-only property count

Use the Boolean property isEmpty to check if the Count property is empty

You can use the subscript syntax in a dictionary to add new data items.

airports["LHR"] = "London"

You can also use subscript syntax to change the value of a specific key

airports["LHR"] = "London Heathrow"

As another subscript method, the dictionary of the Updatevalue (_:forkey:) The method can set or update the value corresponding to a particular key, which sets a new value when the key does not exist, or updates the existing value when it exists.

Updatevalue (_:forkey:) method returns an optional value of the type of the corresponding value, for example: for a dictionary that stores string values, the function returns a string? Or, optionally, a value of type string. If a value exists before the update, the optional value contains the old value, otherwise it will be nil

If Let OldValue = Airports.updatevalue ("Dublin Airport", Forkey: "DUB") {

Print ("The old value for DUB is \ (oldValue).")

}

We can also use the following banner to Angin the value of a particular key in the dictionary, because there is the possibility that the requested key does not have a corresponding value, the dictionary's subscript access returns an optional value for the type of the corresponding value, and if the dictionary contains a value corresponding to the request key, the next bidding clubs returns an optional value that contains the existing value, otherwise Nil

If let Airportname = airports["DUB"] {

Print ("The name of the airport is \ (airportname).")

} else {

Print ("That airport was not in the airports dictionary.")

}

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"

airports["APL" = nil//APL removed

In addition, RemoveValue (Forkey:) The method can also be used for UI out-of-key-value pairs, which remove the key-value pair if the key-value pair exists, return the removed value, or return nil without a value

If Let Removedvalue = Airports.removevalue (forkey: "DUB") {

Print ("The removed airport ' s name is \ (removedvalue).")

} else {

Print ("The Airports Dictionary does not contain a value for DUB.")

}

//

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 in the form of (key, value) tuples, and we can use temporary constants or variables to decompose these tuples:

//

For (Airportcode, Airportname) in airports {

Print ("\ (Airportcode): \ (airportname)")

//}

Yyz:toronto Pearson

Lhr:london Heathrow

For more information on for-in loops, see for loops.

//

By accessing the keys or the Values property, we can also traverse the dictionary key or value:

//

For Airportcode in Airports.keys {

Print ("Airport code: \ (Airportcode)")

//}

Airport Code:yyz

Airport CODE:LHR

//

For Airportname in Airports.values {

Print ("Airport name: \ (airportname)")

//}

Airport Name:toronto Pearson

Airport Name:london Heathrow

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

//

Let airportcodes = [String] (Airports.keys)

Airportcodes is ["YYZ", "LHR"]

//

Let airportnames = [String] (airports.values)

Airportnames is ["Toronto Pearson", "London Heathrow"]

The dictionary type of Swift is an unordered collection type. To traverse the key or value of a dictionary in a specific order, you can use the sorted () method on the keys or values property of the dictionary.

Swift Learning-05--Collection type

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.