字典Dictionary与NSDictionary

与Oc的字典不太一样,Swift的字典不仅可以存储 对象类型的值,还可以存储 基本数据类型值,结构体,枚举值;

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来修改其值

用最多的梦面对未来

字典Dictionary与NSDictionary

相关文章:

你感兴趣的文章:

标签云: