zoukankan      html  css  js  c++  java
  • Swift-Dictionary

    1、字典写法

    Dictionary<KeyType,ValueType>,KeyType是你想要储存的键,ValueType是你想要储存的值。

    唯一的限制就是KeyType必须是可哈希的,就是提供一个形式让它们自身是独立识别的

    Swift的全部基础类型都能够

    2、创建字典

    var airport :Dictionary<String, String> = ["TYO": "Tokyo", "DUB": Dublin"]
    
    var namesOfIntegers = Dictionary<Int, String>()
    namesOfIntegers[16] = "sixteen"

    3、字典元素个数

    airports.count
    4、字典加入�一个元素

    airports["LHR"] = "London"
    5、使用下标语法去改变一个特定键所关联的值。

    airports["LHR"] = "London Heathrow"
    updateValue(forKey:) 方法返回一个和字典的值同样类型的可选值. 
    比如,假设字典的值的类型时String,则会返回String? 或者叫“可选String“,这个可选值包括一个假设值发生更新的旧值和假设值不存在的nil值。        
    if let oldValue = airports.updateValue("Dublin International", forKey: "DUB") {
    println("The old value for DUB was (oldValue).")
    }
    6、获取key所相应的值

    let airportName = airports["DUB"]
    使用下标语法把他的值分配为nil,来移除这个键值对。

    7、移除key相应的值

    airports["APL"] = "Apple International"
    // "Apple International" 不是 APL的真实机场,所以删除它
    airports["APL"] = nil
    从一个字典中移除一个键值对能够使用removeValueForKey方法,这种方法假设存在键所相应的值,则移除一个键值对,并返回被移除的值,否则返回nil。
    let removedValue = airports.removeValueForKey("DUB")
    8、用for in遍历字典

    for (airportCode, airportName) in airports {
    println("(airportCode): (airportName)")
    }
    读取字典的keys属性或者values属性来遍历这个字典的键或值的集合。

    for airportCode in airports.keys {
    println("Airport code: (airportCode)")
    }
    // Airport code: TYO
    // Airport code: LHR
    for airportName in airports.values {
    println("Airport name: (airportName)")
    }
    使用keys或者values属性来初始化一个数组

    let airportCodes = Array(airports.keys)
    let airportNames = Array(airports.values)

  • 相关阅读:
    上传图片时判断图片的模式GRB或CMYK
    正则表达式的6中使用
    SqlServer获得存储过程的返回值
    从零学习wcf(一)
    等比例缩小图片
    模仿Jquery Tab
    jquery ajax调用一般处理程序
    一种感觉
    "敏捷软件开发" 读书笔记叙
    荣迁贵宝地
  • 原文地址:https://www.cnblogs.com/yxwkf/p/3860229.html
Copyright © 2011-2022 走看看