专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > Swift

Swift课程13-字典Dictionary与NSDictionary

发布时间:2011-06-30 07:27:57 文章来源:www.iduyao.cn 采编人员:星星草
Swift教程13-字典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来修改其值


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.LazyBidirectionalCollection
Swift.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["数学"] = nil
println(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

           







友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: