• <small id="w8oog"></small>
  • <td id="w8oog"></td>
  • <small id="w8oog"></small><xmp id="w8oog"><td id="w8oog"></td><td id="w8oog"><li id="w8oog"></li></td><xmp id="w8oog"><td id="w8oog"></td>
  • <td id="w8oog"></td><td id="w8oog"><li id="w8oog"></li></td><small id="w8oog"></small>
  • <td id="w8oog"></td>
  • <small id="w8oog"></small>
  • <small id="w8oog"></small><td id="w8oog"></td>
    免費開源的iOS開發學習平臺

    Swift: 5.3 集合類型-字典

    字典類型就是存儲一組相關聯的鍵值對(key-value),key的值是唯一的。字典中的鍵值對是無序的。

    • 字典類型使用 Dictionary<Key, Value>進行初始化,如果上下文中Key,Value的類型可以推斷出來,也可以簡寫成[:]。字典類型可以通過下標進行賦值,如果下標值不存在,則插入,否則就是更新值。不過字典類型中,還提供了updateValue(_:forKey:)函數來更新值,該函數有返回值,如果被更新的Key已經存在,則返回舊值,如果不存在則返回nil??梢酝ㄟ^給賦值nil來刪除字典中的某個鍵值對。也可以通過removeValue(forKey:)函數來刪除某個鍵值對,同樣的,這個函數也有返回值,如果刪除成功,就返回被刪除的值,如果失敗就返回nil。字典類型的循環遍歷跟數組也類似,循環的每個項是個(key,value)的元組。
    //初始化
    var intStringDic = [Int:String]()
    intStringDic = [:]
    var fruits = ["Apple":"蘋果","Juice":"橘子","Bananas":"香蕉"]
    
    //插入和刪除
    intStringDic[10] = "Ten"
    fruits["Orange"] = "橙色的"
    fruits["Orange"] = "橙子"
    fruits["Orange"] = nil
    
    //使用函數進行更新和刪除
    if let oldValue = fruits.updateValue("APP", forKey: "Apple") {
        print("更新前的值是: \(oldValue).")
    }
    if let removedValue = fruits.removeValue(forKey: "Orange") {
        print("刪除前的值是: \(removedValue).")
    } else {
        print("fruits字典里面沒有Orange這個鍵值")
    }
    
    //循環遍歷
    for (itemKey, itemValue) in fruits {
        print("\(itemKey): \(itemValue)")
    }
    
    //字典類型的keys和values屬性返回字典的鍵值的無序集合,可以轉為數組
    let keys = [String](fruits.keys)
    let values = [String](fruits.values)
    

    示例代碼運行結果如下圖。

    示例代碼

    https://github.com/99ios/23.5.3

    ijzzijzzij亚洲大全|天天狠天天透天干天天|日本一本加勒比五月天伊人久久|久久久噜噜噜久久中文字幕色伊伊
  • <small id="w8oog"></small>
  • <td id="w8oog"></td>
  • <small id="w8oog"></small><xmp id="w8oog"><td id="w8oog"></td><td id="w8oog"><li id="w8oog"></li></td><xmp id="w8oog"><td id="w8oog"></td>
  • <td id="w8oog"></td><td id="w8oog"><li id="w8oog"></li></td><small id="w8oog"></small>
  • <td id="w8oog"></td>
  • <small id="w8oog"></small>
  • <small id="w8oog"></small><td id="w8oog"></td>