美文网首页iOS点滴记录
Swift 3.0学习笔记_5_数组

Swift 3.0学习笔记_5_数组

作者: henu_Larva | 来源:发表于2017-04-10 15:05 被阅读1次
    //Swift 语言提供 Arrays 、 Sets 和 Dictionaries 三种基本的集合类型用来存储集合数据。数组(Arrays)是有序数据的集。集合(Sets)是无序无重复数据的集。字典(Dictionaries)是无序的键值对的集。
    
    //如果创建一个 Arrays 、 Sets 或 Dictionaries 并且把它分配成一个变量,这个集合将会是可变的。如果我们把 Arrays 、 Sets 或 ionaries 分配成常量,那么它就是不可变的,它的大小和内容都不能被改变。
    
    //数组: 数组使用有序列表存储同一类型的多个值。相同的值可以多次出现在一个数组的不同位置中。
    var someInts = [Int]() //类型为 [Int] 的(空)数组
    someInts.append(3) //soemInts 内包含一个元素
    someInts = [] //此时 someInts 为空数组
    
    //创建一个带有默认值的数组
    var threeDoubles = Array(repeating:0.0,count:3) //等价于 [0.0, 0.0, 0.0]
    
    //通过两个数组相加创建一个数组
    var anotherThreeDoubles = Array(repeating:2.5,count:3)
    var sixDoubles = threeDoubles + anotherThreeDoubles //[Double]类型
    
    //字面量构造数组
    var shoppingList:[String] = ["Eggs","Milk","Apples","Books","else"] //等价于: var shoppingList = ["Eggs","Milk"]
    
    //访问和修改数组
    //1.通过只读属性 count 获取数组元素个数
    let count = shoppingList.count
    //2.使用布尔属性 isEmpty 检测数组元素是否为 0
    if shoppingList.isEmpty {
        print("The shopping list is empty")
    } else {
        print("The shopping list is not empty")
    }
    //3.使用 append(_:) 方法在数组后面添加新的数据项
    shoppingList.append("Flour")
    //4.使用 += 也可以直接在数组后面添加一个或多个拥有相同类型的数据项
    shoppingList += ["Bakeing Powder","Cheese"]
    //5.可以直接使用下标语法获取数组中的数据项
    var firstItem = shoppingList[0]
    firstItem = shoppingList.first! //注意这里的感叹号!!!
    
    shoppingList[0] = "Six eggs" //通过索引修改某个元素的值,但是,不可以通过下标的方式在数组尾部添加新数据项
    
    //调用 insert(_:at:)方法可在某个具体的索引之前添加数据项
    shoppingList.insert("Maple Syrup", at: 0)
    //调用 remove(at:)方法可移除数组中的某一项
    shoppingList.remove(at: 0)
    print(shoppingList)
    
    shoppingList.removeLast() //移除最后一项
     shoppingList.removeLast(2) //删除数组的后几个元素
    
    shoppingList.removeFirst() //移除第一项
    print(shoppingList)
    shoppingList.removeFirst(2) //从数组第一个元素开始向后删除的个数. 该语句的意思是,删除 shoppingList的前两个元素
    print(shoppingList)
    
    
    //数组的遍历
    //1.for-in
    for item in shoppingList {
        print(item)
    }
    //2.enumerated() 可同时获得元素的 下标 和 值
    for (index,value) in shoppingList.enumerated() {
        print("Item \(String(index+1)): \(value)")
    }
    

    相关文章

      网友评论

        本文标题:Swift 3.0学习笔记_5_数组

        本文链接:https://www.haomeiwen.com/subject/xxisattx.html