標籤:swift字典 dictionary與nsdiction
與Oc的字典不太一樣,Swift的字典不僅可以儲存 物件類型的值,還可以儲存 基礎資料型別 (Elementary Data Type)值,結構體,枚舉值;
Swift字典的使用方式也更加簡潔,功能更加強大.
字典本質上也是結構體,查看文檔可以看到:
/// A hash-based mapping from `Key` to `Value` instances. Also a/// collection of key-value pairs with no defined ordering.struct Dictionary<Key : Hashable, Value> : CollectionType, DictionaryLiteralConvertible { typealias Element = (Key, Value) typealias Index = DictionaryIndex<Key, Value> /// Create a dictionary with at least the given number of /// elements worth of storage. The actual capacity will be the /// smallest power of 2 that's >= `minimumCapacity`. init() /// Create a dictionary with at least the given number of /// elements worth of storage. The actual capacity will be the /// smallest power of 2 that's >= `minimumCapacity`. init(minimumCapacity: Int) /// The position of the first element in a non-empty dictionary. /// /// Identical to `endIndex` in an empty dictionary /// /// Complexity: amortized O(1) if `self` does not wrap a bridged /// `NSDictionary`, O(N) otherwise. var startIndex: DictionaryIndex<Key, Value> { get } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. /// /// Complexity: amortized O(1) if `self` does not wrap a bridged /// `NSDictionary`, O(N) otherwise. var endIndex: DictionaryIndex<Key, Value> { get } /// Returns the `Index` for the given key, or `nil` if the key is not /// present in the dictionary. func indexForKey(key: Key) -> DictionaryIndex<Key, Value>? subscript (position: DictionaryIndex<Key, Value>) -> (Key, Value) { get } subscript (key: Key) -> Value? /// Update the value stored in the dictionary for the given key, or, if they /// key does not exist, add a new key-value pair to the dictionary. /// /// Returns the value that was replaced, or `nil` if a new key-value pair /// was added. mutating func updateValue(value: Value, forKey key: Key) -> Value? /// Remove the key-value pair at index `i` /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count`\ ). mutating func removeAtIndex(index: DictionaryIndex<Key, Value>) /// Remove a given key and the associated value from the dictionary. /// Returns the value that was removed, or `nil` if the key was not present /// in the dictionary. mutating func removeValueForKey(key: Key) -> Value? /// Remove all elements. /// /// Postcondition: `capacity == 0` iff `keepCapacity` is `false`. /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count`\ ). mutating func removeAll(keepCapacity: Bool = default) /// The number of entries in the dictionary. /// /// Complexity: O(1) var count: Int { get } /// Return a *generator* over the (key, value) pairs. /// /// Complexity: O(1) func generate() -> DictionaryGenerator<Key, Value> /// Create an instance initialized with `elements`. init(dictionaryLiteral elements: (Key, Value)...) /// True iff `count == 0` var isEmpty: Bool { get } /// A collection containing just the keys of `self` /// /// Keys appear in the same order as they occur as the `.0` member /// of key-value pairs in `self`. Each key in the result has a /// unique value. var keys: LazyBidirectionalCollection<MapCollectionView<[Key : Value], Key>> { get } /// A collection containing just the values of `self` /// /// Values appear in the same order as they occur as the `.1` member /// of key-value pairs in `self`. var values: LazyBidirectionalCollection<MapCollectionView<[Key : Value], Value>> { get }}
可以看到 字典的key必須是實現了 Hashable協議的類型;也就是說key的類型不僅限於 字串!
1.字典的聲明
//定義一個空的字典var dic:[String:Int]=[:]
形式:
var dicName:[key類型 : 值類型]
或者,使用範型的方式類約束其類型
//字典的範型定義方式var myDic:Dictionary<String,String>
2.字典的建立.
(1)我們觀察上面給出的 字典定義可以看到有兩個init 方法,這是兩個構造器,我們可以使用這兩個構造器來建立字典對象
init()
<span style="font-family: Arial, Helvetica, sans-serif;">init(minimumCapacity: Int)</span>
第二個構造器指定了 字典的最小容量
//使用init()構造器var mydic:[String:String]=Dictionary<String,String>()
//使用init(minimumCapacity:Int)var dic2:[String:Int]dic2=Dictionary<String,Int>(minimumCapacity: 5)
(2)直接賦值建立字典
var myDic:Dictionary<String,String>myDic=["語文":"99","數學":"100"];
3.字典或數組的判空操作
isEmpty
是用該屬性返回的布爾值,可以判斷數組或字典中的元素個數是否為0
4.訪問或修改字典的元素
(1)字典可以直接通過類似下標的方式 key來訪問,字典的元素;var 定義的可變字典可以直接使用Key來修改其值
var myDic:Dictionary<String,String>myDic=["語文":"99","數學":"100"];myDic["語文"]="99.9222"//可變字典可以直接修改內容println(myDic["語文"])
輸出:
Optional("99.9222")
可以看到,通過 key我們拿到的是一個 可選類型,我們需要對其進行解析;因為 該key對應的值可能不存在!!!
(2) 解析可選類型值
我們必須使用可選類型來接收 Key對應的值,否則會導致編譯錯誤
var yuwen:String? = myDic["語文"]
完整樣本:
var myDic:Dictionary<String,String>myDic=["語文":"99","數學":"100"];myDic["語文"]="99.9222"//可變字典可以直接修改內容var yu:String? = myDic["語文"]if yu != nil{ println(yu!)}
輸出:
99.9222
可以看到,我們把之前的可選類型解析為我們需要的普通類型,就可以直接使用了
5.修改,新增字典元素的幾種方式
(1)可以直接使用 下標方式,形如
dic["key"] = value 的形式來修改或新增字典元素;如果該key對應的元素不存在則會新增這個key的鍵值對,否則會直接修改該key對應的值;
var myDic:Dictionary<String,String>myDic=["語文":"99","數學":"100"];println(myDic)myDic["2語文"]="99.9222"println(myDic)
輸出:
[數學: 100, 語文: 99][數學: 100, 語文: 99, 2語文: 99.9222]
上面的 key "2語文" 在 原來的字典中並不存在,此時會新增一個 元素,對應的 key是 該 "2語文",值 是 "99.922"
(2)使用字典的方法
mutating func updateValue(value: Value, forKey key: Key) -> Value?
使用樣本:
var myDic:Dictionary<String,String>myDic=["語文":"99","數學":"100"];println(myDic)myDic.updateValue("888", forKey: "新增的key")println(myDic)
輸出:
[數學: 100, 語文: 99][新增的key: 888, 數學: 100, 語文: 99]
可以看到,此方法對於 不存在的 key也會新增 鍵值對;當然如果該 key存在就會直接修改該key對應的值
6.擷取所有的keys和 values, 方法 和 Oc中的方法類似
查看 字典的定義文檔可以知道 如下的 兩個屬性,可以獲得所有的 keys 和 values
var keys: LazyBidirectionalCollection<MapCollectionView<[Key : Value], Key>> { get } /// A collection containing just the values of `self` /// /// Values appear in the same order as they occur as the `.1` member /// of key-value pairs in `self`. var values: LazyBidirectionalCollection<MapCollectionView<[Key : Value], Value>> { get }
使用方法:
var myDic:Dictionary<String,String>myDic=["語文":"99","數學":"100"];println(myDic.keys)println(myDic.values)
輸出:
Swift.LazyBidirectionalCollectionSwift.LazyBidirectionalCollection
可以看到,輸出的是集合類型;如果我們想要看到它的值,則可以把它放在數組中即可:
var myDic:Dictionary<String,String>myDic=["語文":"99","數學":"100"];var keys1 = Array(myDic.keys)println(keys1)var values1 = Array(myDic.values)println(values1)
輸出,所有keys values
[數學, 語文][100, 99]
7.刪除字典元素的幾種方式
(1)刪除單個數組元素
可以使用 dic[key] = nil來刪除一個元素
或者使用 removeValueForKey方法來刪除
var myDic:Dictionary<String,String>myDic=["語文":"99","數學":"100"];myDic.removeValueForKey("語文")println(myDic)myDic["新增"] = "77"println(myDic)myDic["數學"] = nilprintln(myDic)
[數學: 100][數學: 100, 新增: 77][新增: 77]
(2)清空字典元素
var myDic:Dictionary<String,String>myDic=["語文":"99","數學":"100"];myDic = [:]println(myDic)
直接 把字典賦值為 空
myDic = [:]即可
或者:
var myDic:Dictionary<String,String>myDic=["語文":"99","數學":"100"];myDic.removeAll(keepCapacity: false)println(myDic)
對於 keepCapacity :false /true ,根據需求選擇 即可;
區別是true的話,會保持資料容量,佔據空間?
8.字典的複製
字典的複製規律和數組類似
如果字典內的元素是實值型別的,如整型,那麼字典複製時,會把源字典複製出元素的副本;如果字典內的元素是參考型別的,如對象,那麼 字典複製時,只是複製出元素的指標,修改該指標則也會修改源字典的內容
關於Swift數組請參見http://blog.csdn.net/yangbingbinga/article/details/44747877
更多Swift教程:http://blog.csdn.net/yangbingbinga
Swift教程13-字典Dictionary與NSDictionary