Swift - 字典中的存储值顺序完全改变 [英] Swift - Stored values order is completely changed in Dictionary

查看:58
本文介绍了Swift - 字典中的存储值顺序完全改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图显示字典格式的数据.下面是三种尝试.第一次尝试,输出顺序完全改变.第二次尝试,输出顺序与输入相同.但是,在第三次尝试中,我将变量声明为 NSDictionary.我收到的确切输出.为什么这会在字典中发生变化?请指导我.我搜索了 Swift 的 Dictionary 标签.但我找不到.

I tried to display datas which is in Dictionary format. Below, three attempts are there. First attempt, output order is completely changed. Second attempt, output order is same as input. But, in third attempt, I declared variable as NSDictionary. Exact output I received. Why this changes in Dictionary? Kindly guide me. I searched for Swift's Dictionary tag. But I couldn't found out.

//First Attempt
var dict : Dictionary = ["name1" : "Loy", "name2" : "Roy"]
        println(dict)

//output:
[name2: Roy, name1: Loy]

//Second Attempt
var dict : Dictionary = ["name2" : "Loy", "name1" : "Roy"]
        println(dict)

//output:
[name2: Loy, name1: Roy]
-----------------------------------------------------------

//Third Attempt With NSDictionary
var dict : NSDictionary = ["name1" : "Loy", "name2" : "Roy"]
            println(dict)

//output:
{
    name1 = Loy;
    name2 = Roy;
}

ANOTHER QUERY:我已使用 Playground 进行验证.我的屏幕截图如下:

ANOTHER QUERY: I have used play ground to verify. My screen shot is below:

这里,在 NSDictionary 中,我首先给出了 name5,但是在右侧 name2 显示,然后,在 println 中,它是按升序显示的.为什么会这样??

Here, In NSDictionary, I gave name5 as first, but in right side name2 is displaying, then, in println, it is displaying in ascending order. Why this is happening??

在这里,在字典中,我首先给出了 name5,但在右侧显示了 name2,然后,在 println 中,它显示了它在 Dictionary 行上的显示方式.为什么会这样??

Here, In Dictionary, I gave name5 as first, but in right side name2 is displaying, then, in println, it is displaying, how it is taken on the Dictionary line. Why this is happening??

推荐答案

这是因为 Dictionaries 的定义:

This is because of the definition of Dictionaries:

字典存储集合中相同类型的键和相同类型的值之间的关联,没有定义的顺序.

A dictionary stores associations between keys of the same type and values of the same type in an collection with no defined ordering.

没有没有顺序,它们的输出可能与放入时不同.
这与 NSSet 相当.

There is no order, they might come out differently than they were put in.
This is comparable to NSSet.

字典收集键值对.NSDictionary 不是简单地维护一个有序或无序的对象集合,而是根据给定的键存储对象,然后可以将其用于检索.

Dictionaries Collect Key-Value Pairs. Rather than simply maintaining an ordered or unordered collection of objects, an NSDictionary stores objects against given keys, which can then be used for retrieval.

没有顺序,但是为了调试目的,有打印排序.

There is also no order, however there is sorting on print for debugging purposes.

这篇关于Swift - 字典中的存储值顺序完全改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆