十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
在foundation框架中,提供一种字典类,它是由键值对构成的集合,键和值集合的元素可以可以是任何对象,但是不能nil,Foundation框架字典也分为NSDictionary 不可变字典和 NSMutableDictionary可变字典
目前创新互联建站已为1000多家的企业提供了网站建设、域名、网站空间、网站运营、企业网站设计、新源网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。
一、NSDictationary类
NSDictionary有很多方法和属性,以下是常见的:
1、-initWithDictionary 构造器,通过swift的Dictionary创建NSDictionary对象
2、-initWithObjects:forKeys 构造器,通过键集合和值集合创建NSDictionary对象
3、-count 字典集合的长度
4、-objectForKeys 通过键获得值对象
5、allKeys 返回所有键集合
示例
let keyString:NSString = "1 2 3 4 5" var keys:NSArray = keyString.componentsSeparatedByString(" ") let valueString:NSString = "alpha bravo charlie delta echo" var values:NSArray = valuesString.componentsSeparatedByString(" ") var dict:NSDictationary = NSDictionary(object:values,forKeys:kes) NSLog("%@",dict.description) var value:NSString = dict.objectForKey("3") as NSString NSLog("%@",value) var kys= dict.allKeys for item:AnyObject in kys{ var key = item as NSString NSLog("%@,%@",key,dict.objectForKey(key) as NSString) }
二、NSMutableDictionary类
NSMutableDictionary类是NSDictionary类的子类,有很多方法和属性,以下是常用的:
1、-setObjectForKey
2、-removeObjectForKey 按照键移除值
示例
var mutable:NSMutableDictionary = NSMutableDictionary(); mutable.setObject("TOM",forKey:"tom@xx.com") mutable.setObject("BOB",forKey:"bob@xx.com") NSLog("%@",mutable.description) var keys= mutable.allKeys for item:AnyObject in keys { var key = item as NSString NSLog("%@,%@",key,mutable.objectForKey(key) as NSString) }
三、NSDictionary 与 Dictionary
NSDictionary 与 Dictionary之间的关系类似于NSArray和Array之间的关系,swift能够在底层将它们自动桥接起来,一个NSDictionary对象桥接之后的结果是[NSObject:AnyObject]
示例:
let keyString:NSString = "1 2 3 4 5" var keys:NSArray = keyString.componentsSeparatedByString(" ") let valueString:NSString = "Alpha bravo charlie delta echo" var values:NSArray = valueString.componentsSeparatedByString(" ") let foundationDict:NSDictionary = NSDictionary(objects:values,forKeys:keys) let swiftDict:Dictionary = foundationDict println(swiftDict.description) let value:AnyObject? = swiftDict["3"] println("value") for (key,value) in swiftDict { println("\(key):\(value)") }