集合类型-day01

来源:互联网 发布:数据新闻手册 编辑:程序博客网 时间:2024/06/06 20:36

A.  数组

1.   创建数组

      a.  Array 创建一个特定大小并且有默认大小的数组

     var threeDoubles = Array(repeating:0.0,count:3)               //repeating  默认值   count 个数

    // threeDoubles是一种[Double]数组,等价于[0.0, 0.0, 0.0] 

    b.  用数组字面量构造数组

   varshoppingList: [String] = ["Eggs","Milk"

2.   两个数组相加

varanotherThreeDoubles = Array(repeating:2.5,count:3)

varsixDoubles = threeDoubles + anotherThreeDoubles

// sixDoubles被推断为[Double],等价于[0.0, 0.0, 0.0, 2.5, 2.5, 2.5] 


3. 数组的操作

  array.isEmpty                             //数组是否为空

  array.append("Flour")            //array 数组后添加一项

  array += ["Baking Powder"]      //+= 号运算


 a. 批量修改数组内容





b. 插入

shoppingList.insert("Maple Syrup", at: 0)           // at  插入位置


c. 数组遍历

for (index, value) in shoppingList. enumerated() {    print("Item \(String(index + 1)): \(value)")

}

// Item 1: Six eggs// Item 2: Milk// Item 3: Flour// Item 4: Baking Powder// Item 5: Bananas


B.字典

1.  创建字典

    varnamesOfIntegers = [Int: String]()            //创建一个 key为int 类型,值为string类型的空字典

    namesOfIntegers[16] ="sixteen"                  // 加入一个键值对

    namesOfIntegers = [:]                                // namesOfIntegers 现在包含一个键值对  namesOfIntegers = [:] 

   varairports: [String: String] = ["YYZ":"Toronto Pearson","DUB":"Dublin"]             //  创建一个 key和为string 类型字典


 2. 更新字典  updateValue

  如果字典中存在该key ,更新该key对应的键值,并返回该key;如果不存在,则插入该键值对,没有返回值

      var shopDics = [1:2,3:4,5:6]  

   a. 不存在该key

      if let oldValue  =shopDics.updateValue(100, forKey:7){

        print(oldValue)

     }

    // shopDics 为 [1:2,3:4,5:6,7:100]    oldValue为nil   


   b. 存在该key

      if let oldValue  = shopDics.updateValue(100, forKey:3){

      print(oldValue)

     }

    //oldValue 为3   [1:2,3:100,5:6]


3. 字典操作

   移除键值对

   var shopDics = [1:2,3:4,5:6]

   shopDics[3] = nil                             //  shopDics 值为 [1:2,5:6] 

     let removedValue = shopDics. removeValue(forKey: 1 )      //   移除该键值对,并返回删除前该key对应的value 值         removedValue 为2

4.字典遍历

a. 输出全部  

for (key,value)inshopDics

{

    print("key:\(key) value:\(value)")

}

b. 输出value

for value inshopDics.values

{

    print(value)

}


c. 输出 key

for keyinshopDics.keys

{

    print(key)

}








原创粉丝点击