集合类型-day01

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)

}








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值