zoukankan      html  css  js  c++  java
  • Swift-4-数组和字典

    // Playground - noun: a place where people can play
    
    import UIKit
    
    // 数组 字典
    // 集合的可变性 赋值给var的集合是可变的mutable,赋值给let的集合是不可变的immutable
    // 数组   Array<SomeType> 等价于 [SomeType]
    var shoppingList : [String] = ["Eggs", "Milk"] // var shoppingList = ["Eggs", "Milk"] 自动推断类型
    // 数组计数
    println("the shopping list contains (shoppingList.count) items")
    
    // 检查数组是否为空
    if shoppingList.isEmpty {
        println("the shopping list is empty")
    } else {
        println("the shopping list is not empty")
    }
    
    // 向数组中添加元素
    shoppingList.append("Flour")
    shoppingList += ["Baking Powder"]
    
    // 访问数组中元素
    var firstItem = shoppingList[0]
    
    // 批量替换数组中元素 用于替换的数组元素个数与替换的范围不一定要相同
    shoppingList[1...2] = ["Apples"]
    
    // 插入元素
    shoppingList.insert("Maple Syrup", atIndex: 0)
    
    // 从数组中移除元素
    let mapleSyrup = shoppingList.removeAtIndex(0)
    shoppingList.removeRange(Range(start: 1, end: 2))
    shoppingList.removeLast()
    
    // 遍历数组
    for item in shoppingList {
        println(item)
    }
    
    for (index, item) in enumerate(shoppingList) {
        println("Item (index + 1): (item)")
    }
    
    // 创建并初始化数组
    var someInts = [Int]()
    println("someInts is of type [Int] with (someInts.count) items")
    
    // 创建数组时赋默认值
    var thressDoubles = [Double](count: 5, repeatedValue: 0.0)
    
    // 组合数组
    var anotherDoubles = [Double](count: 3, repeatedValue: 0.1)
    var eightDouble = thressDoubles + anotherDoubles
    
    // 字典
    //Dictionary<key, value>  [key  : value]
    var airports: [String : String] = ["YYZ" : "Toronto Pearson", "DUB" : "Dublin"] // var airports = ["YYZ" : "Toronto Pearson", "DUB" : "Dublin"]
    
    // 访问、修改字典
    println("The airports dictionary contains (airports.count) items")
    
    if airports.isEmpty {
        println("The airports dictionary is empty")
    } else {
        println("The airports dictionary is not empty")
    }
    
    // 添加元素
    airports["LHR"] = "London"
    airports["LHR"] = "London Heathrow"
    
    // 通过方法设置键值. 返回被替换的value optional
    let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB")
    
    // 移除键值对
    airports["DUB"] = nil
    airports.removeValueForKey("DUB")
    
    // 遍历
    for (key, value) in airports {
        println("key: (key), value: (value)")
    }
  • 相关阅读:
    苹果p12文件--一个苹果证书怎么多次使用(蛋疼,这些问题只有和其他企业合作才会遇到,别人的账号不可能给你,蛋疼....)
    xcode 树形管理 cocos2d-x的资源
    cocos2d-x 扩充引擎基类功能 引起的头文件重复包含问题的分析
    pytest--运行指定的测试和参数化
    adb--常用命令
    appium--desktop
    adb--环境安装
    pytest--命令行常用参数
    django -- auth模块
    pytest--常用插件
  • 原文地址:https://www.cnblogs.com/liufeng24/p/4117179.html
Copyright © 2011-2022 走看看