Swift 字典(Dictionary)

字典是一种可以储存相同的类型多重数据储存其,每个值(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 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'."


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值