Swift教程13-字典Dictionary与NSDictionary

Swift教程13-字典Dictionary与NSDictionary,第1张

概述与Oc的字典不太一样,Swift的字典不仅可以存储 对象类型的值,还可以存储 基本数据类型值,结构体,枚举值; Swift字典的使用方式也更加简洁,功能更加强大. 字典本质上也是结构体,查看文档可以看到: /// A hash-based mapping from `Key` to `Value` instances. Also a/// collection of key-value pai

与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 >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,"数学":"100"];myDic["语文"]="99.9222"//可变字典可以直接修改内容println(myDic["语文"])

输出:
Optional("99.9222")

可以看到,通过 key我们拿到的是一个 可选类型,我们需要对其进行解析;因为 该key对应的值可能不存在!!!


(2) 解析可选类型值


我们必须使用可选类型来接收 Key对应的值,否则会导致编译错误

var yuwen:String? = myDic["语文"]

完整示例:
var myDic:Dictionary<String,"数学":"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,"数学":"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],Value>> { get }

使用方法:
var myDic:Dictionary<String,"数学":"100"];println(myDic.keys)println(myDic.values)

输出:
Swift.LazyBIDirectionalCollectionSwift.LazyBIDirectionalCollection

可以看到,输出的是集合类型;如果我们想要看到它的值,则可以把它放在数组中即可:
var myDic:Dictionary<String,"数学":"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,"数学":"100"];myDic.removeValueForKey("语文")println(myDic)myDic["新增"] = "77"println(myDic)myDic["数学"] = nilprintln(myDic)

[数学: 100][数学: 100,新增: 77][新增: 77]


(2)清空字典元素


var myDic:Dictionary<String,"数学":"100"];myDic = [:]println(myDic)

直接 把字典赋值为 空


myDic = [:]即可


或者:

var myDic:Dictionary<String,"数学":"100"];myDic.removeAll(keepCapacity: false)println(myDic)

对于 keepCapacity :false /true,根据需求选择 即可;

区别是true的话,会保持数据容量,占据空间?


8.字典的复制


字典的复制规律和数组类似


如果字典内的元素是值类型的,如整型,那么字典复制时,会把源字典复制出元素的副本;如果字典内的元素是引用类型的,如对象,那么 字典复制时,只是复制出元素的指针,修改该指针则也会修改源字典的内容

关于Swift数组请参见http://www.jb51.cc/article/p-qciqfodx-oh.html


更多Swift教程:http://blog.csdn.net/yangbingbinga

总结

以上是内存溢出为你收集整理的Swift教程13-字典Dictionary与NSDictionary全部内容,希望文章能够帮你解决Swift教程13-字典Dictionary与NSDictionary所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/1088288.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-27
下一篇2022-05-27

发表评论

登录后才能评论

评论列表(0条)

    保存