标签:swift视频 swift swift教程 ios8 ios
在Foundation框架中提供一种字典集合,它是由“键-值”对构成的集合。键集合不能重复,值集合没有特殊要求。键和值集合中的元素可以是任何对象,但是不能是nil。Foundation框架字典类也分为NSDictionary不可变字典和NSMutableDictionary可变字典。NSDictionary有很多方法和属性,下面总结其常用的方法和属性。
initWithDictionary: 构造器,通过Swift的Dictionary创建NSDictionary对象。
initWithObjects:forKeys: 构造器,通过键集合和值集合创建NSDictionary对象。import Foundation let keyString : NSString = "one two three four five" ① var keys : NSArray = keyString.componentsSeparatedByString(" ") ② let valuestring : NSString = "alpha bravo charlie delta echo" ③ var values : NSArray = valuestring.componentsSeparatedByString(" ") ④ vardict : NSDictionary = NSDictionary(objects: keys, forKeys:values) ⑤ NSLog("%@", dict.description) ⑥ varvalue:NSString = dict.objectForKey("three") as NSString ⑦ NSLog("three = %@", value) varkys = dict.allKeys ⑧ for item : AnyObject in kys { ⑨ var key = item as NSString NSLog("%@ - %@", key, dict.objectForKey(key) as NSString) }
2014-07-06 20:19:07.274 PlaygroundStub_OSX[4110:303] { five = echo; four = delta; one = alpha; three = charlie; two = bravo; } 2014-07-06 20:19:07.281 PlaygroundStub_OSX[4110:303] three = charlie 2014-07-06 20:19:07.296 PlaygroundStub_OSX[4110:303] one - alpha 2014-07-06 20:19:07.300 PlaygroundStub_OSX[4110:303] five - echo 2014-07-06 20:19:07.305 PlaygroundStub_OSX[4110:303] three - charlie 2014-07-06 20:19:07.308 PlaygroundStub_OSX[4110:303] two - bravo 2014-07-06 20:19:07.313 PlaygroundStub_OSX[4110:303] four - delta
import Foundation var mutable : NSMutableDictionary = NSMutableDictionary() ① // add objects mutable.setObject("Tom", forKey: "tom@jones.com") ② mutable.setObject("Bob", forKey: "bob@dole.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) }
2014-07-06 20:42:11.596 PlaygroundStub_OSX[4332:303] { "bob@dole.com" = Bob; "tom@jones.com" = Tom; } 2014-07-06 20:42:11.605 PlaygroundStub_OSX[4332:303] bob@dole.com - Bob 2014-07-06 20:42:11.608 PlaygroundStub_OSX[4332:303] tom@jones.com – Tom
import Foundation ① let keyString : NSString = "one two three four five" let keys : NSArray = keyString.componentsSeparatedByString(" ") let valueString : NSString = "alpha bravo charlie delta echo" let values : NSArray = valueString.componentsSeparatedByString(" ") let foundationDict : NSDictionary = NSDictionary(objects:values, forKeys:keys) ② let swiftDict : Dictionary = foundationDict ③ println(swiftDict.description) let value: AnyObject? = swiftDict["three"] ④ println("three = \(value)") for (key, value) in swiftDict { ⑤ println ("\(key) - \(value)") }
第④行代码是从Dictionary字典取three键对应的值,它的类型是可选的AnyObject类型,这是因为有可能取不到这个值。第⑤行代码是遍历Dictionary字典键和值集合。
欢迎关注智捷iOS课堂微信公共平台
标签:swift视频 swift swift教程 ios8 ios
原文地址:http://blog.csdn.net/tonny_guan/article/details/39122955