Swift Learning note seven: Collection

Source: Internet
Author: User
Tags array sort

Arrays Array

    • Creation of arrays
      • Use @[] to define an array in OC, using [] to define an array in Swift
      • [Type] means that all elements of that type are stored in the array.
      • Elements in the array in Swift can be basic data types
//Create an arrayvar array1:array<int>Vararray2:array<Int> = [2,3]var array3: [Int]var array33=[Int] () array1= Array (arrayliteral:1,2,3,4) var array4= Array (Repeatelement ("A", Count:Ten)) Vararray44= Array (repeating:0.0, Count:3) //create an empty arrayvar array5:array<int> =[]var array6: [Int]=Array ()//if the types in the data are inconsistent, specify the type array<any>Let array7:array<any> = ["1",1, p]
    • Traversal of an array
//1. Follow the subscript traversal forIinch 0.. <array.count{Print (Array[i])}//2. for in traversal forIincharray{Print (i)}//3. Enum block traversal, while traversing subscript and element forIincharray.enumerated () {print (i)}//4. Traversing subscripts and elements for(Index, Element)incharray.enumerated () {print ("\ (index)---\ (element)")}  //5. Reverse-order Traversal forIincharray.reversed () {print (i)} forSincharray.enumerated (). Reversed () {print (s)}

    • Merging additions and deletions of arrays
//OC Medium-Number component variable Nsmutablearray ()/Immutable Nsarray ()//array variable var/immutable let in Swiftvar arr = ["1","2","3"] //Append ElementArr.append ("0") //Modify, Position by subscriptarr[0] ="AAA"  //array out of bounds---Index outof Range//array[5] = "XXX"//DeleteArr.remove (at:3) //Delete all, and reserve spaceArr.removeall (keepingcapacity:true)  //Array Mergingvar arr1 = ["3"," One","2"]var arr2= ["AAA","CCC","BB","FFF"] //Note: The two types of arrays to be merged must be consistentarr1 + = arr2
    • Sorting of arrays
// Array Sorting 1 2 3 4  //  array Sort By default is ascending order  //  descending arrangement array1.sort (by: >   //  ascending arrangement Array1.sort (by: <)

Dictionary Dictionary
    • OC definition Dictionary @{}, Swift definition dictionary [key:value]
// the declaration of the Dictionary and the creation of var dic1:dictionary<int, string>= Dictionary (dictionaryliteral: (1,"  1"), (2,"2"= [1:"  1 ", 2:"2"]var dic5 = [int:string] ()

    • Dictionary additions and Deletions change
var dict: [String:any] = ["name":"Zhang"," Age": -] //new and modified in the dictionary is the value of the key: If the key exists, it is modified, if the key does not exist, it means that the new//Newdict["title"] ="AAA"  //Modifydict["name"] ="Li"Dict.updatevalue ("00000000", Forkey:"name") Dict.updatevalue ("PPP", Forkey:"XXX")  //Delete: If there is a corresponding key, then delete, if not the corresponding key, do not operateDict.removevalue (Forkey:" Age") print (dict) dict.removevalue (forkey:" Age") print (dict)

    • The traversal of a dictionary
Let Dict1: [String:any] = ["name":"Zhang"," Age": -,"title":"name"]  forEinchdict1{print (e)} for(Key, value)inchdict1{Print ("\ (key)---\ (value)")}  //Mergingvar dict3: [String:any] = ["name":"Zhang"," Age": -,"title":"name"]let DICT4: [String:any]= ["name":"Li","Height":1.8] //Traverse, and then click Set for(Key, value)inchdict4{Dict3[key]=Value}

Set set
    • Creation of Set
// Create collection var set1:set<int> = [1234]var set2:set<string > = Set (arrayliteral:"1","2","3  "= Set (arrayliteral:1,2,3)  var set4:set <Int> = []

    • Common operations for collections
//get the number of elementsSet1.count//determines whether the collection is an empty collectionifset1.isempty{Print ("collection is empty")} //determines whether an element is contained in the collectionifSet1.contains (2) {print ("contains this element in the collection")} //InsertSet1.insert (5) //gets the subscript at the specified positionvar setindex = Set1.index (of:4)//removes the element that specifies the subscriptSet1.remove (at:setindex!) //removing the specified elementSet1.remove (1)
    • Mathematical operations of sets
var setn:set<int> = [1,2,3,4,5,6]varsetm:set<Int> = [4,5,6,7,8] //perform a intersection operation: Take the intersection of two setsvar setinter =setn.intersection (Setm)//make symmertricdifference take two different parts of the collectionvar setdif =setn.symmetricdifference (Setm)//Union of the collection, and setvar Setuni =setn.union (Setm)//subtracting operations for collections: Use a set to intercept another collectionvar setsub =setn.subtracting (Setm) Setn==Setm var setsub1:set<Int> = [1,2,3] //determines whether a subset or parent setSetsub1.issubset (OF:SETN) setn.issuperset (OF:SETSUB1)//determine if a true subset or true parent setSetsub1.isstrictsubset (OF:SETN) setn.isstrictsuperset (OF:SETSUB1)

    • Traversal of a collection
 var setsub1:set<int> = [1 , 2 , Span style= "COLOR: #800080" >3  ]  for  Item in   setsub1{print (item)}  for  item in   Setsub1.enumerated () {print (item)}  for  (Index, item) in   setsub1.enumerated () {print ( "  \ (index): \ (item)   "  for  index in  Span style= "COLOR: #000000" > setsub1.indices{print (Setsub1[index])}  

Swift Learning note seven: Collection

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.