Swift Learning Note (5): Collection type

Source: Internet
Author: User

Directory:

    • Arrays: Array
    • Set: Set
    • Dictionary: Dictionary

Swift provides three basic collection types for array (ordered collection data), set (unordered No Duplicates collection), and dictionary (unordered key-value pairs collection) to store collection data of explicit data types.

Using Var to declare a collection as a variable, you can add, remove, and modify data items within the collection after creation. If you use let to declare a collection as a constant, its size and content are immutable.

Arrays: Array

Initialize and assign values:

var someints = [Int] ()//creates an empty array of the specified data typeSomeints = []//to assign a null value to data of a known data type//Threedoubles is a [Double] array, equivalent to [0.0, 0.0, 0.0]var threedoubles = Array (repeating:0.0, Count:3)//to create data with default values//Sixdoubles is inferred as [Double], equivalent to [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]var anotherthreedoubles = Array (repeating:2.5, Count:3)var sixdoubles = threedoubles + anotherthreedoubles//combine two arrays of the same data type by +var shoppinglist = ["Eggs","Milk"]//array literal constructs an arrayvar shoppinglist: [String] = ["Eggs","Milk"]//equivalent to the above

We can use subscripts or properties and methods to access and modify arrays:

Shoppinglist.count//gets the number of array elements//Use the IsEmpty property to determine whether the array book is emptyifShoppinglist.isempty {Print"The shopping list is empty.")}Shoppinglist.append ("Flour")//appending data elements using the Append () methodShoppinglist + = ["Chocolate Spread","Cheese","Butter"]//Append Data elements with + =var FirstItem = shoppinglist[0]//using array subscripts to access elements, the first item is "Eggs"shoppinglist[0] ="Six Eggs"     //use subscript to change array elementsshoppinglist[4...6] = ["Bananas","Apples"]//Replace the 3 elements of 4~6 with the 2 elements on the rightShoppinglist.insert ("Maple Syrup", at:0)// Use the Insert (_:at:) method to add elements before a specific indexLet Maplesyrup = Remove (at:0)//to remove an indexed array elementLet apples = shoppinglist.removelast ()//move the last element of the divisor group

Attention:

? You cannot add a new item at the end of the array by using the Subscript access form
The array start index is 0 and the maximum index is count-1

To iterate through an array using for-in:

 for inch shoppinglist {    print (item)}

Use the array enumerated () method to iterate through an array to return element values and indexes:

 for inch shoppinglist. enumerated () {    print ("Item \ (String (index + 1)): \ (value)"  )}//  item 1:six eggs//  Item 2:milk//  Item 3:flour c14>//  Item 4:baking Powder//  Item 5:bananas

Set: Set

A type of data needs to be stored in the set, and the type must be hashed and the hash value type int. Swift basic data types can be hashed, and enumerations with no associated values can also be hashed.

Custom data types You must implement the hashable and equatable protocols of the Swift language when you want to save as a set element.

Initialize and assign values:

var letters = set<character> ()//Create an empty sets collectionLetters = []//known data type, assign an empty sets collection, letters remains set<character> type//construct a collection using array literalsvar favoritegenres:set = ["Rock","Classical","Hip Hop"]var Favoritegenres:set<String> = ["Rock","Classical","Hip Hop"]

To access and modify a set collection:

Favoritegenres.count//gets the number of elements of the set collection//Use the IsEmpty property to determine if the set collection is emptyiffavoritegenres.isempty {print ("as far as the music goes, I ' m not picky.")}favoritegenres.insert ("Jazz")//inserting a set collection elementLet removedgenre = Favoritegenres.remove ("Rock")//Delete a set collection elementFavoritegenres.removeall ()//Delete all elements of a collection//use the Contains () method to determine whether the set collection contains the specified elementifFavoritegenres.contains ("Funk") {print ("I get up on the good foot.")}

To traverse a set collection using for-in:

 for inch favoritegenres {    print ("\ (genre)")}

Use sorted () to return a sorted number to traverse the Set collection:

 for inch favoritegenres.sorted () {     print ("(genre)")}//  Prints "classical"//  prints "Hip Hop"//  prints "Jazz

Dictionary: Dictionary

Initialize and assign values:

var namesofintegers = [Int:string]//Create an empty dictionaryNamesofintegers = [:]//assigning null values to a dictionary of known data types//literal constructs a dictionaryvar airports = ["YYZ":"Toronto Pearson","DUB":"Dublin"]var Airports: [string:string]= ["YYZ":"Toronto Pearson","DUB":"Dublin"]

To access and modify the dictionary collection:

Airports.count//get the number of dictionary elements//Determine if the dictionary is emptyifairports.isempty {print ("The airports Dictionary is empty.")}airports["LHR"] ="London"  //use subscript to assign or change values for the specified key dictionary element//Use the Updatevalue () method of the dictionary to update the dictionary elements and verify the update resultsifLet OldValue = Airports.updatevalue ("Dublin Airport", Forkey:"DUB") {print ("The old value is DUB was (oldValue).")}//determines whether the specified key associated element exists in the dictionaryifLet Airportname = airports["DUB"] {print ("The name of the Airport is (airportname).")}airports["APL"] = Nil//Delete dictionary Specifies the element associated with key//Use the dictionary Removedvalue () method to delete the specified element and verify the delete resultifLet Removedvalue = airports. RemoveValue (Forkey:"DUB") {print ("The removed airport ' s name is (removedvalue).")}

To traverse a dictionary using for-in:

 for inch Airports {    print ("(Airportcode): (airportname)")}// Yyz:toronto Pearson // Lhr:london Heathrow

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

 forAirportcodeinchAirports.keys {print ("Airport Code: (airportcode)")}//Airport Code:yyz//Airport CODE:LHR forAirportnameinchairports.values {print ("Airport Name: (airportname)")}//Airport Name:toronto Pearson//Airport Name:london Heathrow

Statement: This series of content is from the network or electronic books, only to do learning summary!

Swift Learning Note (5): 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.