你好,歡迎來到IOS教程網

swift

編輯:IOS技巧綜合
[摘要]本文是對swift-字典的講解,對學習IOS蘋果軟件開發有所幫助,與大家分享。

swift字典

    在swift中,key:key值一定是可hash的,一定是獨一無二的,swift的基本數據類型(String,Int,Float)都是可哈希的,所以都可以作為key值。 value:沒有要求

    直接上代碼了,注釋給大家標的很明白

    //創建字典並賦值
    let dict = ["name":"xiaoyu","age":12]
    let dict2:[String:Any] = ["name":"xiaoyu","age":12];
    let dict3:Dictionary<String,Any> = ["name":"xiaoyu","age":13,"height":130]
    
    print(dict3)
    
    //創建空字典
    
    let dict4:[String:Any] = [:]
    let dict5:[String:Any] = Dictionary()
    
    //創建可變字典
    var dict6:[String:Any] = ["name":"xiaoyu"]
    
    //更新字典的數據 value輸出的是原來的key對應的value值
    if let Value = dict6.updateValue("dayu", forKey: "name")
    {
        print(Value)
        print(dict6)
    }
    
    //刪除字典元素
    dict6.removeValueForKey("name")
    //刪除全部元素
    dict6.removeAll()
    dict6.removeAll(keepCapacity: true)
    //遍歷字典
    for (key,value) in dict6
    {
        print("key:\(key) value:\(value)")
    }
    
    for key in dict6.keys{
        print("key:\(key)")
    }
    
    //合並字典
    
    var dict7:[String:Any] = ["name":"小雨","age":133]
    
    var newDict8:[String:Any] = ["weight":"小於","height":13]
    for (key,value) in newDict8{
        dict7.updateValue(value, forKey: key)
    }
    
    print("dict7:\(dict7)");
  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved