Swift Learning notes-4. Collection type

Source: Internet
Author: User

Array

simple syntax for arraysWrite arrays should follow the form of array<sometype>, or you can use simple syntax such as [SomeType]. It is recommended to use a shorter array to construct the statement array literal: [Value1, Value2, Value3] var shoppinglist: [String] = ["Eggs", "Milk"]because of the type inference mechanism, we do not have to write out the type definition of an array when we construct only the same type values using literal constructs. You can also write this: var shoppinglist = ["Eggs", "Milk"]
Accessing and modifying arrays(1) 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 system property count to get the number of data items in the array. println ("The shopping list contains \ (shoppinglist.count) Items") (2) Use IsEmpty to check if the data item is 0 if Shoppinglist.isempty {
println ("The shopping list is empty")
} else {
println ("The shopping list is not empty")
} (3) You can use the Append method to add a new data item after the array shoppinglist.append ("Flour") (4) Using + = or you can add one or more data items with the same type after the array: shoppinglist + = ["Baking Powder "]
Shoppinglist + = ["Chocolate Spread", "Cheese", "Butter"] (5) You can use subscript syntax to get a data item, or modify the data value corresponding to an index value var FirstItem = shoppinglist[0 ]shoppinglist[0] = "Six eggs" (6) the subscript can be used to change a series of data values at once, even if the new data and the original data are not the same amount. SHOPPINGLIST[4...6] = ["Banana", "Apples"] (7) Call Inser (Atindex:) Method adds a data item before a specific index value shoppinglist.insert ("Maple syrup", atindex:0) (8) You can also use the Removeatindex method to set an item in a group. Remove an item and return the removed data item let Maplesyrup = Shoppinglist.removeatindex (0) Let apples = Shoppinglist.removelast () traversal of an array(1) iterating through the For In loop
For item in Shoppinglist {
println (item)
} (2) If you need both the value of each data item and the index value, you 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.
For (index, value) in enumerate (shoppinglist) {
println ("Item \ (index + 1): \ (value)")
} Create and construct an arrayUse construct syntax to create an empty array var someints = [Int] ()
println ("someints is of type int[] with \ (someints.count) items") If type information is provided in the code context, such as a function parameter or a constant or variable of a defined type, You can use an empty array statement to create an empty array, which is simple: [] someints.append (3)
Someints = [] The Array type also provides a constructor method that can create a specific size and all data is default. The number of data items that are ready to be added to the new array (count) and the initial value of the appropriate type (Repeatedvalue) are passed into the array constructor: var threedoubles = [Double] (Count:3, repeatedvalue:0.0) Because of type inference, you can also write this directly: var anotherthreedouble = Array (count:3, repeatedvalue:2.5) Finally, you can use "+" to combine two existing arrays of the same type. The type of the new array is inferred from the data type of the two arrays: var sixdoubles = threedoubles + anotherthreedouble DictionaryThe use of Swift's dictionaries requires specifying the types of keys and values that can be stored. Swift's Dictionary uses dictionary<keytype, valuetype> definitions, and you can also use short syntax [Keytype:valuetype]. Definition dictionary: [key 1:value 1, key 2:value 2, key 3:value 3] var airports: [String:string] = ["Tyo": "Tokyo", "DUB": "Dubliln"] As with arrays, it is not necessary to define the type clearly if the dictionary is constructed using literal literals. Airports can also be defined as: var airports2 = ["Tyo": "Tokyo", "DUB": "Dubliln"] reading and modifying dictionaries(1) and arrays, you can get the number of data items for a dictionary by using the dictionary's read-only property count: println ("The Airports Dictionary contains \ (airports.count) items")(2) Use IsEmpty to determine if Count is 0:if airports.isempty {
println ("The Airports Dictionary is empty.")
} else {
println ("The Airports Dictionary is not empty.")
} (3) We can also add new data items by using subscript syntax, or change the corresponding data item airports["LHR"] = "London" airports["LHR"] = "London Heathrow" (4) Updatevalue (Forkey :) method to set or update the value corresponding to a specific key. However, unlike the subscript method, this function returns the original value before the updated value. Updatevalue (Forkey:) Returns an optional value that contains a dictionary value type. If Let OldValue = Airports.updatevalue ("Dublin International", Forkey: "DUB") {
println ("The old value for DUB is \ (oldValue)")
} (5) You can use the following banner to retrieve the value corresponding to a specific value in the dictionary. The value is returned if the value corresponding to the key exists. Otherwise returns nil if let Airportname = airports["DUB"] {
println ("The name of the airport is \ (airportname)")
} else {
println ("That airport was not in the Airports dictionary")
} (6) You can also use subscript syntax to remove a key-value pair from the dictionary by assigning a value of nil to a key value: airports["APL"] = nil (7) The Removevalueforkey method can also be used to remove key-value pairs in the dictionary. This method removes the key-value pair if the key-value pair exists, and returns the removed value or nil if let Removedvalue = Airports.removevalueforkey ("DUB") without a value {
println ("The removed airport ' s name is \ (removedvalue)")
} else {
println ("The Airports Dictionary does not contain a value for DUB")
} Traverse Dictionary  We can use for in to traverse a key-value pair in a dictionary. The data items in each dictionary are returned in the form of (key,value) tuples, and they can be decomposed using temporary constants or variables. For (Airportcode, Airportname) in airports {
println ("\ (Airportcode): \ (airportname)")
We can also retrieve the key or value for a dictionary by accessing its keys or the Values property (both of which are ergodic collections) for Airportcode in Airports.keys {
println ("Airport code: \ (Airportcode)")
}

For Airportname in Airports.values {
println ("Airport name: \ (airportname)")
If you just need to use a dictionary key-value pair or a value collection as a parameter to accept the array instance API, you can use the keys or the values property to construct a new array directly let Airportcodes = [String] (Airports.keys)
Let airportnames = [String] (airports.values) Create an empty dictionaryWe can also create an empty dictionary using the construct syntax like an array: var namesofintegers = [Int:string] () If the context already provides the information type, we can use the empty dictionary literal to create an empty dictionary, which is written as: [:] NAMESOFINTEGERS[16] = "Sixteen"
Namesofintegers = [:]

Swift Learning notes-4. 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.