Swift 字典(Dictionary)

来源:互联网 发布:linux deamon 编辑:程序博客网 时间:2024/04/29 08:43

字典是一种可以储存相同的类型多重数据储存其,每个值(value)都关联特定的健(key),健作为这个字典中的典型的标识符。和数组中的数组项不同,字典中的值是无序的,我们在需要通过标识符访问数据的时候使用字典,这和我们现实中的查字典是一样的。

 

Swift的字典使用时需要具体规定可以存储健值的类型不同与OCNSDictionaryNSMutableDictionary类可以使用任何类型的对象来作健和值并且不提供任何关于这些对象的本质信息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 codein 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'."


0 0
原创粉丝点击