在foundation框架中,提供一种字典类,它是由键值对构成的集合,键和值集合的元素可以可以是任何对象,但是不能nil,Foundation框架字典也分为NSDictionary 不可变字典和 NSMutableDictionary可变字典
一、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)") }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。