您好,登錄后才能下訂單哦!
在foundation框架中,提供一種字典類,它是由鍵值對構(gòu)成的集合,鍵和值集合的元素可以可以是任何對象,但是不能nil,F(xiàn)oundation框架字典也分為NSDictionary 不可變字典和 NSMutableDictionary可變字典
一、NSDictationary類
NSDictionary有很多方法和屬性,以下是常見的:
1、-initWithDictionary 構(gòu)造器,通過swift的Dictionary創(chuàng)建NSDictionary對象
2、-initWithObjects:forKeys 構(gòu)造器,通過鍵集合和值集合創(chuàng)建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之間的關(guān)系類似于NSArray和Array之間的關(guān)系,swift能夠在底層將它們自動(dòng)橋接起來,一個(gè)NSDictionary對象橋接之后的結(jié)果是[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)") }
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。