字典在快速迭代时返回连续/混洗的值 [英] Dictionary returns consecutive/shuffled values when iterating in swift

查看:48
本文介绍了字典在快速迭代时返回连续/混洗的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字典

var data : [String: String] = ["DEV" : "DEV", "QUA" : "QUA" , "SIT" : "SIT", "UAT" : "UAT", "PROD" : "PROD"]

我使用 for 循环迭代它并获得以下值

I Iterate it using for loop and get the following values

SIT
PROD
DEV
UAT
QUA

即连续值

我有以下代码来迭代它

for (key, value ) in data.enumerate()
{
    print(value)
}

我想以相同的声明格式获取这些值.

I want to get these values in same format of declaration.

推荐答案

Swift Dictionary 类型是无序类型.在每个 for in 循环中,您可以收到不同的有序结果(理论上).如果你想保持顺序,你应该选择其他数据结构,Array<(String, String)> 例如:

Swift Dictionary type is unordered type. On every for in loop you can receive different ordered result (in theory). You should choose other data structure if you wish to keep order, Array<(String, String)> for example:

var data: Array<(String, String)> = [("DEV", "DEV"), ("QUA", "QUA"), ("SIT", "SIT"), ("UAT", "UAT"), ("PROD", "PROD")]

for element in data {
    print(element.1)
}
//DEV
//QUA
//SIT
//UAT
//PROD

这篇关于字典在快速迭代时返回连续/混洗的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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