天天看點

Swift 字典(Dictionary)

字典是一種可以儲存相同的類型多重資料儲存其,每個值(value)都關聯特定的健(key),健作為這個字典中的典型的辨別符。和數組中的數組項不同,字典中的值是無序的,我們在需要通過辨別符通路資料的時候使用字典,這和我們現實中的查字典是一樣的。

Swift的字典使用時需要具體規定可以存儲健值的類型,不同與OC的NSDictionary和NSMutableDictionary 類可以使用任何類型的對象來作健和值并且不提供任何關于這些對象的本質資訊,在swift中,在某個特點的字典中可以存儲的健和值必須是字典可以儲存的健和值必須提前定義清楚,方法是通過顯性類型标注或者類型的推斷。

Swift的字典使用NSDictionary<KeyType,ValueType>其中KeyType是字典中的惡資料類型,,ValueType是字典中對于這些健鎖儲存值的資料類型

KeyType的唯一限制就是客哈希的,這樣可以保證它是獨一無二的,所有的swift基本類型預設可哈希的,并且這些類型都可以在字典中使用,為關聯的枚舉成員也是預設哈希的

//建立字典

var responseMessage:Dictionary<Int,String> = [200 : "OK", 403 : "access", 404: "found", 500 : "error"];

var responseMessagetwo= [200 : "OK", 403 : "access", 404: "found", 500 : "error"]

//建立一個空的字典

var emptyDic:[String: String] = [:]

print(responseMessage[200]); //"Optional("OK")\n"

let htttpResponseCodes= [200, 403, 301]

for code in htttpResponseCodes {

    if let message = responseMessage[code] {

        print("response \(code): \(message)");

    } else {

        print("\(code)");

   }

}

//修改字典

responseMessage[404] = "move"

print(responseMessage[404])  // "Optional("move")\n"

responseMessage[404] = "not found"

print(responseMessage) //"[500: "error", 200: "OK",403: "access", 404: "not found"]\n"

let imagePath = ["star":"png", "portrait":"jpg", "sepcer":"gif"];

for (name, path) in imagePath {

    print("The path to '\(name)' is '\(path)'.")

}

//Prints "The path to 'star' is '/glyphs/star.png'."

//Prints "The path to 'portrait' is '/images/content/portrait.jpg'."

//Prints "The path to 'spacer' is '/images/shared/spacer.gif'."