iOS - Swift Dictionary 字典


前言

	public struct Dictionary<Key : Hashable, Value> : CollectionType, DictionaryLiteralConvertible
	public class NSDictionary : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSFastEnumeration
  • 字典用於存儲無序的數據元素值,它可以存儲任何類型的元素,甚至可以將數組作為字典的元素。

1、Dictionary 與 NSDictionary 的相互轉換

  • Dictionary 與 NSDictionary 之間可以直接相互轉換。Dictionary 轉轉成 NSDictionary 時,數組中的各項元素被轉換為 AnyObject 類型。NSDictionary 轉換成 Dictionary 時,數組中的各項元素也被轉換為 AnyObject 類型。
	let dictinoary:[String:String] = ["key1":"value1", "key2":"value"]
	    
	// Dictionary 轉 NSDictionary
		    
		// Dictionary 轉換成 NSDictionary<AnyObject, AnyObject> 型
		let nsDictionary1:NSDictionary = dictinoary
		
		// Dictionary 轉換成 NSDictionary<AnyObject, AnyObject> 型
		let nsDictionary2:NSDictionary = dictinoary as NSDictionary
		    
	// NSDictionary 轉 Dictionary
		    
		// NSDictionary 轉換成 Dictionary<AnyObject, AnyObject> 型
		let swiftDictionary1:Dictionary = nsDictionary1 as Dictionary
		
		// NSDictionary 轉換成 Dictionary<String, String> 型
		let swiftDictionary2:Dictionary = nsDictionary1 as! [String:String]

2、字典的 創建

	// Dictionary 型字典
		    
		// 創建字典變量,指定數據類型為 Int 型
		let dic1 = [String:Int]()
		
		// 創建字典變量,Dictionary<String, Int> 等價於 [String:Int]
		let dic2 = Dictionary<String, Int>()
		
		// 創建字典變量,不指定數據類型
		let dic3:Dictionary = ["key1":1, "key2":2]
		
		// 創建字典變量,指定數據類型為 Int 型
		let dic4:Dictionary<String, Int> = ["key1":1, "key2":2, "key3":3]
		
		// 創建字典變量,不指定數據類型
		let dic5 = ["key1":1, "key2":2, "key3":3, "key4":4]
		
		// 創建指定數據類型的字典
		let dic6:[String:Int] = ["key1":1, "key2":2, "key3":3, "key4":4]
		
		// 創建指定數據類型的字典
		let dic7:[String:AnyObject] = ["key1":1, "key2":2, "key3":"value3", "key4":4]
			
	// NSDictionary 型字典
		    
		let swiftDictionary = ["key1":1, "key2":2, "key3":3, "key4":4]
		    
		let nsdic1:NSDictionary = swiftDictionary
		let nsdic2:NSDictionary = swiftDictionary as NSDictionary
		    
		let nsdic3:NSDictionary = NSDictionary(dictionary: swiftDictionary)
		let nsdic4:NSDictionary = NSDictionary(dictionary: ["key1":1, "key2":2, "key3":3, "key4":4])
		    
		let nsdic5:NSDictionary = NSDictionary(object: "nsdic5", forKey: "key1")
		let nsdic6:NSDictionary = NSDictionary(objects: ["nsdic6", 2], forKeys: ["key1", "key2"])
		let nsdic7:NSDictionary = NSDictionary(dictionaryLiteral: ("key1", "nsdic7"), 
		                                                          ("key2", 2), 
		                                                          ("key3", 3), 
		                                                          ("key4", 4))
		
		// 從 文件 創建字符串
		let nsdic8:NSDictionary? = NSDictionary(contentsOfFile: NSHomeDirectory() + "/Desktop/test.txt")
		    
		// 從 Url 創建字符串                            
		let nsdic9:NSDictionary? = NSDictionary(contentsOfURL: NSURL(fileURLWithPath: NSHomeDirectory() + 
		                                                                              "/Desktop/test.txt"))

3、字典元素個數的計算

	// Dictionary 或 NSDictionary 型字典
	    
	let dic = ["key1":1, "key2":2, "key3":3, "key4":4]
	    
	let num:Int = dic.count

4、通過 key 找對應的 value

	// Dictionary 型字典
		    
		var dic:Dictionary = ["key1":1, "key2":2, "key3":3, "key4":4]
		    
		// 獲取字典中指定 key 對應的值
		let value1 = dic["key2"]
			
	// NSDictionary 型字典

		let nsDic:NSDictionary = NSDictionary(dictionary: ["key1":1, "key2":2, "key3":3, "key4":4])
		    
		// 獲取字典中指定 key 對應的值
		let value2:AnyObject? = nsDic["key2"]
		
		// 獲取字典中指定 key 對應的值
		let value3:AnyObject? = nsDic.objectForKey("key2")
		
		// 獲取字典中指定 key 對應的值,key 的值不存在時返回指定的字符串
		let value4 = nsDic.objectsForKeys(["key3", "key4", "key5"], notFoundMarker: "not found")

5、通過 value 找對應的 key

	// NSDictionary 型字典
		    
		let nsDic:NSDictionary = NSDictionary(dictionary: ["key1":1, "key2":3, "key3":3, "key4":4])
		    
		let keys:AnyObject = nsDic.allKeysForObject(3)

6、字典中所有 key 的獲取

	// Dictionary 型字典
		    
		let dic:Dictionary = ["key1":1, "key2":2, "key3":3, "key4":4]
		    
		let keys1 = dic.keys
		
	// NSDictionary 型字典
		    
		let nsDic:NSDictionary = NSDictionary(dictionary: ["key1":1, "key2":2, "key3":3, "key4":4])
		    
		let keys2 = nsDic.allKeys

7、字典中所有 value 的獲取

	// Dictionary 型字典
		    
		let dic:Dictionary = ["key1":1, "key2":2, "key3":3, "key4":4]
		    
		let values1 = dic.values
			
	// NSDictionary 型字典
		    
		let nsDic:NSDictionary = NSDictionary(dictionary: ["key1":1, "key2":2, "key3":3, "key4":4])
		    
		let values2 = nsDic.allValues

8、字典鍵值對的 追加

	// Dictionary 型字典
		    
		var dic:Dictionary = ["key1":1, "key2":2, "key3":3, "key4":4]
		    
		// key 不存在時,追加鍵值對(key 值為新增的,若 key 值已存在則為修改對應的 value 值)
		dic["key5"] = 5
			
	// NSDictionary 型字典
	    
		let nsDic:NSMutableDictionary = NSMutableDictionary(dictionary: ["key1":1, "key2":2, "key3":3, "key4":4])
		    
		// key 不存在時,追加鍵值對(key 值為新增的,若 key 值已存在則為修改對應的 value 值)
		nsDic["key5"] = 5
		
		// 向字典末尾追加一個字典
		nsDic.addEntriesFromDictionary(["key6":6, "key7":7])

9、字典鍵值對的 修改

	// Dictionary 型字典
		    
		var dic:Dictionary = ["key1":1, "key2":2, "key3":3, "key4":4]
		    
		// key 存在時,修改其值
		dic["key4"] = 100
		
		// 修改指定的 key 對應的值
		dic.updateValue(44, forKey: "key4")
			
	// NSDictionary 型字典
	    
		let nsDic:NSMutableDictionary = NSMutableDictionary(dictionary: ["key1":1, "key2":2, "key3":3, "key4":4])
		    
		// key 存在時,修改其值
		nsDic["key3"] = 33
		
		// 修改指定的 key 對應的值
		nsDic.setObject(100, forKey: "key4")
		
		// 修改整個字典
		nsDic.setDictionary(["key6":6, "key7":7])

10、字典鍵值對的 刪除

	// Dictionary 型字典
		    
		var dic:Dictionary = ["key1":1, "key2":2, "key3":3, "key4":4]
		    
		// 刪除指定 key 對應的值
		dic.removeValueForKey("key2")
		
		// 刪除字典的所有元素
		dic.removeAll(keepCapacity: true)
			
	// NSDictionary 型字典
		    
		let nsDic:NSMutableDictionary = NSMutableDictionary(dictionary: ["key1":1, "key2":2, "key3":3, "key4":4])
		    
		// 刪除指定 key 對應的值
		nsDic.removeObjectForKey("key2")
		
		// 刪除指定 key 對應的值
		nsDic.removeObjectsForKeys(["key1", "key4"])
		
		// 刪除字典的所有元素
		nsDic.removeAllObjects()

11、字典遍歷

	// NSDictionary 型字典
		
		let nsDic:NSDictionary = NSDictionary(dictionary: ["key1":1, "key2":2, "key3":3, "key4":4])
		    
		// for...in 循環
			    
			// 遍歷出的為 key-value 的元組, key 不需要可以用 _ 替代
			for (_, obj) in nsDic {
			    
				print(obj)
			}
			    
		// 閉包遍歷
			    
			nsDic.enumerateKeysAndObjectsUsingBlock { (key:AnyObject, obj:AnyObject, stop:UnsafeMutablePointer<ObjCBool>) in
			 
				print(obj)
			}
			    
		// 迭代器遍歷
			    
			// key 迭代器
			
				let keyEnu:NSEnumerator = nsDic.keyEnumerator()
				    
				while let key:AnyObject = keyEnu.nextObject() {
				    
					print(nsDic.objectForKey(key))
				}
			    
			// 對象迭代器
			
				let objEnu:NSEnumerator = nsDic.objectEnumerator()
				    
				while let obj:AnyObject = objEnu.nextObject() {
				    
					print(obj)
				}

12、字典排序

	// NSDictionary 型字典
			
		let nsDic:NSDictionary = NSDictionary(dictionary: ["key1":"value1", "key2":"value2", "key3":"value3", "key4":"value4"])
		    
		// 用閉包排序
			    
			let keys1 = nsDic.keysSortedByValueUsingComparator { (obj1:AnyObject, obj2:AnyObject) -> NSComparisonResult in
			   
				return (obj1 as! String).compare(obj2 as! String)
			}
			    
			for key in keys1 {
				print(nsDic.objectForKey(key))
			}
		    
		// 用指定的方法排序
			    
			let keys2 = nsDic.keysSortedByValueUsingSelector(#selector(NSNumber.compare(_:)))
			    
			for key in keys2 {
				print(nsDic.objectForKey(key))
			}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM