Array

作者: 暖光照 | 来源:发表于2016-10-24 21:14 被阅读0次
可变性

数组的不可变性跟字典略有不同。尽管你不能进行任何可能会改变数组大小的操作,但是你可以给数组中的某个索引设置一个新的值。这使得Swift的数组在大小固定的情况下能够达到最佳的性能

构造数组
    var emptyArray = [Int]()
    
    var emptyArray2 = Array<Int>()
    
    var threeDoubles = [Double](count: 3, repeatedValue:0.0)
    // threeDoubles 是一种 [Double] 数组,等价于 [0.0, 0.0, 0.0]
    
    // anotherThreeDoubles 被推断为 [Double],等价于 [2.5, 2.5, 2.5]
    var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5)
    
    // sixDoubles 被推断为 [Double],等价于 [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
    var sixDoubles = threeDoubles + anotherThreeDoubles
    
    // shoppingList 已经被构造并且拥有两个初始项。
    var shoppingList: [String] = ["Eggs", "Milk"]
    
    //让编译器进行类型判断
    var shoppingList2 = ["Eggs", "Milk"]   
    // 追加单个元素
    shoppingList.append(String(3))
    
    // 追加一个数组
    shoppingList += ["book","chopsticks"]
    
    // 追加一个集合
    shoppingList.appendContentsOf(["cup", "coke"])

    //插入单个元素
    shoppingList.insert("football", atIndex: 2)
   // 删除第一个
    let element = shoppingList.removeAtIndex(0)
    
    // 删除最后一个
    let lastElement = shoppingList.removeLast()
    
    // 删除所有元素,但是内存不释放,空间容量保留
    shoppingList.removeAll(keepCapacity: true)

    // 删除所有元素,且不保留原来的空间
    shoppingList.removeAll(keepCapacity: false)
    
    // 移除位置1、2、3的元素
    shoppingList.removeRange(1...3)
    
    // 移除第一个元素
    let first = shoppingList.removeFirst()
    
    // 移除前三个元素
    shoppingList.removeFirst(3)
   //修改单个元素
    shoppingList[0] = "basketball"
    
    //修改一个区间的元素
    shoppingList.replaceRange(1...2, with: ["Badminton", "ping-pong"])
    //数组元素个数
    print(shoppingList.count)     //2
    //数组是否为空
    print(shoppingList.isEmpty)   //false
    
     //遍历
    for item in shoppingList {
        print(item)
    }
    //带索引的遍历
    for (index, value) in shoppingList.enumerate() {
        print("index: \(index), value = \(value)")
    }  

相关文章

网友评论

      本文标题:Array

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