您好,登錄后才能下訂單哦!
在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。