在foundation框架中,提供一种字典类,它是由键值对构成的集合,键和值集合的元素可以可以是任何对象,但是不能nil,Foundation框架字典也分为NSDictionary 不可变字典和 NSMutableDictionary可变字典


一、NSDictationary类


NSDictionary有很多方法和属性,以下是常见的:


1、-initWithDictionary 构造器,通过swift的Dictionary创建NSDictionary对象

2、-initWithObjects:forKeys 构造器,通过键集合和值集合创建NSDictionary对象

3、-count 字典集合的长度

4、-objectForKeys 通过键获得值对象

5、allKeys 返回所有键集合


示例

letkeyString:NSString="12345"varkeys:NSArray=keyString.componentsSeparatedByString("")letvalueString:NSString="alphabravocharliedeltaecho"varvalues:NSArray=valuesString.componentsSeparatedByString("")vardict:NSDictationary=NSDictionary(object:values,forKeys:kes)NSLog("%@",dict.description)varvalue:NSString=dict.objectForKey("3")asNSStringNSLog("%@",value)varkys=dict.allKeysforitem:AnyObjectinkys{varkey=itemasNSStringNSLog("%@,%@",key,dict.objectForKey(key)asNSString)}





二、NSMutableDictionary类


NSMutableDictionary类是NSDictionary类的子类,有很多方法和属性,以下是常用的:


1、-setObjectForKey

2、-removeObjectForKey 按照键移除值


示例

varmutable:NSMutableDictionary=NSMutableDictionary();mutable.setObject("TOM",forKey:"tom@xx.com")mutable.setObject("BOB",forKey:"bob@xx.com")NSLog("%@",mutable.description)varkeys=mutable.allKeysforitem:AnyObjectinkeys{varkey=itemasNSStringNSLog("%@,%@",key,mutable.objectForKey(key)asNSString)}




三、NSDictionary 与 Dictionary


NSDictionary 与 Dictionary之间的关系类似于NSArray和Array之间的关系,swift能够在底层将它们自动桥接起来,一个NSDictionary对象桥接之后的结果是[NSObject:AnyObject]


示例:


letkeyString:NSString="12345"varkeys:NSArray=keyString.componentsSeparatedByString("")letvalueString:NSString="Alphabravocharliedeltaecho"varvalues:NSArray=valueString.componentsSeparatedByString("")letfoundationDict:NSDictionary=NSDictionary(objects:values,forKeys:keys)letswiftDict:Dictionary=foundationDictprintln(swiftDict.description)letvalue:AnyObject?=swiftDict["3"]println("value")for(key,value)inswiftDict{println("\(key):\(value)")}